ANDROID - Get selected id ratingbar in listview - android

I've tried to find out how to get selected id of the ratingBar in ListView on net, but almost of them using ListViewAdapter or RatingAdapter on another class. I don't know how to do, because I do not yet know about it, so all my classes declared in MainActivity including ListView.
I have a TextView and RatingBar on each list in ListView,
but the issue is how to send each list of RatingBar that already fills into server without create a new class of ListViewAdapter or RatingAdapter??
here is my full code how it's work to display the TextView and RatingBar on each list:
public class Pertanyaan extends AppCompatActivity {
private String TAG = Pertanyaan.class.getSimpleName();
private ProgressDialog pDialog;
private ListView lv;
private Button kirim;
private RatingBar rate;
ArrayList<HashMap<String, String>> contactList;
#Override
public void onBackPressed() {
super.onBackPressed();
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.pertanyaan);
contactList = new ArrayList<>();
TextView textdosen=(TextView)findViewById(R.id.dosen);
TextView textmatkul=(TextView)findViewById(R.id.matkul);
final TextView txtrate=(TextView)findViewById(R.id.txtrating);
kirim = (Button)findViewById(R.id.btn);
rate=(RatingBar)findViewById(R.id.rating);
Bundle b=getIntent().getExtras();
String dosen=b.getString("dosen");
String matkul=b.getString("matkul");
textdosen.setText(dosen);
textmatkul.setText(matkul);
lv = (ListView) findViewById(R.id.list);
new GetContacts().execute();
}
private class GetContacts extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
// Showing progress dialog
pDialog = new ProgressDialog(Pertanyaan.this);
pDialog.setMessage("Menampilkan Pertanyaan...");
pDialog.setCancelable(false);
pDialog.show();
}
#Override
protected Void doInBackground(Void... arg0) {
HttpHandler sh = new HttpHandler();
// Making a request to url and getting response
String url = "http://flix.16mb.com/send_data.php";
String jsonStr = sh.makeServiceCall(url);
Log.e(TAG, "Response from url: " + jsonStr);
if (jsonStr != null) {
try {
JSONArray jsonObj = new JSONArray(jsonStr);
// looping through All Contacts
for (int i = 0; i < jsonObj.length(); i++) {
JSONObject c = jsonObj.getJSONObject(i);
String id = c.getString("id");
String ask = c.getString("ask");
HashMap<String, String> pertanyaans = new HashMap<>();
pertanyaans.put("id", id);
pertanyaans.put("ask", ask);
contactList.add(pertanyaans);
}
} catch (final JSONException e) {
Log.e(TAG, "Json parsing error: " + e.getMessage());
runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(getApplicationContext(),
"Json parsing error: " + e.getMessage(),
Toast.LENGTH_LONG)
.show();
}
});
}
} else {
Log.e(TAG, "Couldn't get json from server.");
runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(getApplicationContext(),
"Couldn't get json from server. Check LogCat for possible errors!",
Toast.LENGTH_LONG)
.show();
}
});
}
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
// Dismiss the progress dialog
if (pDialog.isShowing())
pDialog.dismiss();
/**
* Updating parsed JSON data into ListView
* */
ListAdapter adapter = new SimpleAdapter(
Pertanyaan.this, contactList,
R.layout.list_pertanyaan, new String[]{"ask", "id"}, new int[]{R.id.ask, R.id.txtid});
lv.setAdapter(adapter);
}
}
}
can someone give me a hint what should i do?

Ok here is a sample application so that it should give you some help:
First of all you need to create a CustomAdapter because SimpleAdapter has limitations. Secondly you need to use RecyclerView instead of ListView. After that you need to register a click event when the user clicks on the list that you have made. For those things we come with the following:
The Model of the list:
public class CustomList {
private String id, ask;
public CustomList(String id, String ask) {
this.id = id;
this.ask = ask;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getAsk() {
return ask;
}
public void setAsk(String ask) {
this.ask = ask;
}
}
then the layout for each list item:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="wrap_content">
<LinearLayout
android:orientation="horizontal"
android:layout_width="match_parent"
android:padding="15dp"
android:layout_height="wrap_content">
<TextView
android:text="TextView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/id_text"
android:layout_weight="4" />
<TextView
android:text="TextView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/ask_text"
android:layout_weight="1" />
</LinearLayout>
</LinearLayout>
then the layout for RecyclerView
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="#+id/activity_main"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="kostas.testexample.com.testexample.MainActivity">
<android.support.v7.widget.RecyclerView
android:id="#+id/myRecyclerView"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
</LinearLayout>
then the custom adapter:
public class CustomAdapter extends RecyclerView.Adapter<CustomAdapter.CustomViewHolder>{
private List<CustomList> items;
private Context context;
public CustomAdapter(List<CustomList> items, Context context){
this.items = items;
this.context = context;
}
#Override
public CustomViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.row_item, parent, false);
return new CustomViewHolder(v);
}
#Override
public void onBindViewHolder(CustomViewHolder holder, int position) {
holder.itemId.setText(items.get(position).getId());
holder.itemAsk.setText(items.get(position).getAsk());
}
#Override
public int getItemCount() {
return items.size();
}
#Override
public void onAttachedToRecyclerView(RecyclerView recyclerView) {
super.onAttachedToRecyclerView(recyclerView);
}
class CustomViewHolder extends RecyclerView.ViewHolder {
TextView itemId;
TextView itemAsk;
CustomViewHolder(View itemView) {
super(itemView);
itemId = (TextView)itemView.findViewById(R.id.id_text);
itemAsk = (TextView)itemView.findViewById(R.id.ask_text);
}
}
}
then you add them all up in MainActivity like this:
public class MainActivity extends AppCompatActivity {
private RecyclerView recyclerView;
private LinearLayoutManager layoutManager;
private URL url;
private HttpURLConnection httpURLConnection;
private CustomAdapter customAdapter;
private ProgressDialog pDialog;
private String id, ask;
private List<CustomList> customList = new ArrayList<>();
private StringBuilder jsonResult;
private JSONObject jsonChildNode;
private JSONArray jsonResponse;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
recyclerView = (RecyclerView)findViewById(R.id.myRecyclerView);
layoutManager = new LinearLayoutManager(MainActivity.this, LinearLayoutManager.VERTICAL, false);
recyclerView.setLayoutManager(layoutManager);
recyclerView.setHasFixedSize(true);
recyclerView.setNestedScrollingEnabled(false);
accessWebService();
clickEvent();
}
private void clickEvent() {
recyclerView.addOnItemTouchListener(new RecyclerItemClickListener(MainActivity.this, new RecyclerItemClickListener.OnItemClickListener() {
#Override
public void onItemClick(View view, int position) {
Toast.makeText(MainActivity.this, "Item Clicked at position: " + position + " with id: " + customList.get(position).getId() + " and ask is: " + customList.get(position).getAsk(), Toast.LENGTH_SHORT).show();
}
}));
}
public class JsonReadTask extends AsyncTask<String , Void, List<CustomList>> {
public JsonReadTask() {
super();
}
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(MainActivity.this);
pDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
pDialog.setIndeterminate(true);
pDialog.setMessage("Please Wait");
pDialog.setCancelable(false);
pDialog.setInverseBackgroundForced(true);
// pDialog.show();
}
#Override
protected List<CustomList> doInBackground(String... params) {
try {
url = new URL(params[0]);
httpURLConnection =(HttpURLConnection) url.openConnection();
httpURLConnection.connect();
InputStream in = new BufferedInputStream(httpURLConnection.getInputStream());
jsonResult = inputStreamToString(in, MainActivity.this);
jsonResponse = new JSONArray(jsonResult.toString());
for (int i = 0; i < jsonResponse.length(); i++) {
jsonChildNode = jsonResponse.getJSONObject(i);
id = jsonChildNode.optString("id");
ask = jsonChildNode.optString("ask");
customList.add(new CustomList(id, ask));
}
} catch (IOException | JSONException e) {
e.printStackTrace();
}
return customList;
}
#Override
protected void onPostExecute(List<CustomList> customList) {
if(customList == null){
Log.d("ERORR", "No result to show.");
return;
}
ListDrawer(customList);
pDialog.dismiss();
}
}
public static StringBuilder inputStreamToString(InputStream is, Activity activity) {
String rLine;
StringBuilder answer = new StringBuilder();
BufferedReader rd = new BufferedReader(new InputStreamReader(is));
try {
while ((rLine = rd.readLine()) != null) {
answer.append(rLine);
}
} catch (Exception e) {
activity.finish();
}
return answer;
}
private void ListDrawer(List<CustomList> customList) {
customAdapter = new CustomAdapter(customList, MainActivity.this);
customAdapter.notifyDataSetChanged();
recyclerView.setAdapter(customAdapter);
}
public void accessWebService() {
JsonReadTask task = new JsonReadTask();
task.execute("http://flix.16mb.com/send_data.php");
}
}
and then you need the customListener for RecyclerView
public class RecyclerItemClickListener implements OnItemTouchListener {
private OnItemClickListener mListener;
private OnLongItemClickListener mLongListener;
public interface OnItemClickListener {
public void onItemClick(View view, int position);
}
interface OnLongItemClickListener{
boolean onLongItemClicked(int position);
}
private GestureDetector mGestureDetector;
public RecyclerItemClickListener(Context context, OnItemClickListener listener) {
mListener = listener;
mGestureDetector = new GestureDetector(context, new GestureDetector.SimpleOnGestureListener() {
#Override
public boolean onSingleTapUp(MotionEvent e) {
return true;
}
});
}
public RecyclerItemClickListener(Context context, OnLongItemClickListener listener) {
mLongListener = listener;
mGestureDetector = new GestureDetector(context, new GestureDetector.OnGestureListener() {
#Override
public boolean onDown(MotionEvent e) {
return false;
}
#Override
public void onShowPress(MotionEvent e) {
}
#Override
public boolean onSingleTapUp(MotionEvent e) {
return false;
}
#Override
public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {
return false;
}
#Override
public void onLongPress(MotionEvent e) {
}
#Override
public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
return false;
}
});
}
#Override
public boolean onInterceptTouchEvent(RecyclerView view, MotionEvent e) {
View childView = view.findChildViewUnder(e.getX(), e.getY());
if (childView != null && mListener != null && mGestureDetector.onTouchEvent(e)) {
mListener.onItemClick(childView, view.getChildAdapterPosition(childView));
}
return false;
}
#Override
public void onTouchEvent(RecyclerView view, MotionEvent motionEvent) {
}
#Override
public void onRequestDisallowInterceptTouchEvent(boolean disallowIntercept) {
}
}
which produces the following result:
but do not forget to add to build.gradle(Module: app) the following:
compile 'com.android.support:recyclerview-v7:25.0.1'
and in your Manifest.xml the permission:
<uses-permission android:name="android.permission.INTERNET"/>
Hope it helps and give you a hint on how to do stuff!!!

Related

how can rerun Asynctask inside fragment from recyclerview

I have fragment with Asynctask class which needs to Re-Run the Asynctask from my Recyclerview adapter class.
Note : I want re run asynctask inside of viewHolder.buttonnext.setOnClickListener(new View.OnClickListener() { in onBindViewHolder and when use this line.
new maghalat.GetContacts().execute(); //maghalt is name of fragment contain GetContacts asynctask function
Give me red line under this line without any suggestion
this is my adapter :
public class DataAdapter extends RecyclerView.Adapter<DataAdapter.ViewHolder> {
private Context context;
List<jsonContent> jcontent;
public DataAdapter(Context context, List<jsonContent> jcontent) {
this.context=context;
this.jcontent=jcontent;
}
#Override
public DataAdapter.ViewHolder onCreateViewHolder(ViewGroup viewGroup, int i) {
View view ;
if(i == R.layout.card_row) {
view = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.card_row, viewGroup, false);
}else {
view = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.button_card, viewGroup, false);
}
return new ViewHolder(view);
}
#Override
public void onBindViewHolder(final ViewHolder viewHolder,int i) {
if(i == jcontent.size()) {
viewHolder.buttonnext.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
//try This
((maghalat )context).asyncRun();
}
});
viewHolder.buttonprev.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(context, "pre", Toast.LENGTH_SHORT).show();
}
});
viewHolder.go.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
}
});
viewHolder.cardView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
}
});
viewHolder.pages.setText(Integer.toString(jcontent.get(i-1).pages));
}
else {
viewHolder.title.setText(jcontent.get(i).title);
Picasso.with(context).load(jcontent.get(i).imgurl).resize(300, 400).into(viewHolder.imageView);
}
}
#Override
public int getItemCount() {
return jcontent.size()+1;
}
#Override
public int getItemViewType(int position) {
return (position == jcontent.size()) ? R.layout.button_card : R.layout.card_row;
}
public class ViewHolder extends RecyclerView.ViewHolder{
private TextView title,pages;
private ImageView imageView;
private Button buttonnext,buttonprev,go;
private CardView cardView;
private EditText editText;
public ViewHolder(final View view) {
super(view);
title = (TextView)view.findViewById(R.id.post_title);
imageView=(ImageView)view.findViewById(R.id.img);
buttonnext =(Button)view.findViewById(R.id.next);
buttonprev=(Button)view.findViewById(R.id.prev);
go=(Button)view.findViewById(R.id.go);
editText=(EditText)view.findViewById(R.id.et_go_page);
cardView=(CardView)view.findViewById(R.id.cvv);
pages=(TextView)view.findViewById(R.id.number_pages);
}
}
}
this is my fragment :
public class maghalat extends Fragment {
private RecyclerView recyclerView;
private DataAdapter adapter;
private View myFragmentView;
private String TAG = MainActivity.class.getSimpleName();
private ProgressDialog pDialog;
private int numpage=0;
public int sag;
private String url = "http://memaraneha.ir/category/%d9%85%d9%82%d8%a7%d9%84%d8%a7%d8%aa/page/"+String.valueOf(sag)+"/?json=get_posts";
List<jsonContent> listcontent=new ArrayList<>();
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
myFragmentView = inflater.inflate(R.layout.maghalat, container, false);
if(isNetworkConnected()) {
asyncRun();
}else
{
Toast.makeText(getActivity().getApplicationContext(), "دستگاه شما به اینترنت متصل نیست!", Toast.LENGTH_LONG).show();
}
return myFragmentView;
}
public void asyncRun(){
new GetContacts().execute();
}
public class GetContacts extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
// Showing progress dialog
pDialog = new ProgressDialog(getActivity());
pDialog.setMessage("Please wait...");
pDialog.setCancelable(false);
pDialog.show();
}
#Override
protected Void doInBackground(Void... arg0) {
HttpHandler sh = new HttpHandler();
sag=numpage+1;
// Making a request to url and getting response
String jsonStr = sh.makeServiceCall(url);
Log.e(TAG, "Response from url: " + jsonStr);
if (jsonStr != null) {
try {
JSONObject jsonObj = new JSONObject(jsonStr);
int id=jsonObj.getInt("pages");
JSONArray posts = jsonObj.getJSONArray("posts");
for (int i = 0; i < posts.length(); i++) {
JSONObject c = posts.getJSONObject(i);
jsonContent jsonContent=new jsonContent();
jsonContent.title=c.getString("title");
//img
JSONObject post_img=c.getJSONObject("thumbnail_images");
for (int j=0;j<post_img.length();j++)
{
JSONObject v=post_img.getJSONObject("mom-portfolio-two");
jsonContent.imgurl=v.getString("url");
}
jsonContent.pages=id;
listcontent.add(jsonContent);
}
} catch (final JSONException e) {
Log.e(TAG, "Json parsing error: " + e.getMessage());
getActivity().runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(getActivity().getApplicationContext(),
"Json parsing error: " + e.getMessage(),
Toast.LENGTH_LONG)
.show();
}
});
}
} else {
Log.e(TAG, "Couldn't get json from server.");
getActivity().runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(getActivity().getApplicationContext(),
"Couldn't get json from server. Check LogCat for possible errors!",
Toast.LENGTH_LONG)
.show();
}
});
}
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
pDialog.dismiss();
recyclerView=(RecyclerView)myFragmentView.findViewById(R.id.recycler_view);
recyclerView.setHasFixedSize(true);
RecyclerView.LayoutManager layoutManager = new LinearLayoutManager(getActivity().getApplicationContext());
recyclerView.setLayoutManager(layoutManager);
adapter=new DataAdapter(getActivity(),listcontent);
recyclerView.setAdapter(adapter);
}
}
private boolean isNetworkConnected() {
ConnectivityManager cm = (ConnectivityManager) getActivity().getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo ni = cm.getActiveNetworkInfo();
if (ni == null) {
// There are no active networks.
return false;
} else
return true;
}
}
public class DataAdapter extends RecyclerView.Adapter<DataAdapter.ViewHolder> {
private Context context;
List<jsonContent> jcontent;
private maghalat fragment;
public DataAdapter(Context context, List<jsonContent> jcontent, maghalat frag) {
this.context=context;
this.jcontent=jcontent;
this.fragment = frag;
}
#Override
public DataAdapter.ViewHolder onCreateViewHolder(ViewGroup viewGroup, int i) {
View view ;
if(i == R.layout.card_row) {
view = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.card_row, viewGroup, false);
}else {
view = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.button_card, viewGroup, false);
}
return new ViewHolder(view);
}
#Override
public void onBindViewHolder(final ViewHolder viewHolder,int i) {
if(i == jcontent.size()) {
viewHolder.buttonnext.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
//try This
(fragment).asyncRun();
}
});
viewHolder.buttonprev.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(context, "pre", Toast.LENGTH_SHORT).show();
}
});
viewHolder.go.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
}
});
viewHolder.cardView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
}
});
viewHolder.pages.setText(Integer.toString(jcontent.get(i-1).pages));
}
else {
viewHolder.title.setText(jcontent.get(i).title);
Picasso.with(context).load(jcontent.get(i).imgurl).resize(300, 400).into(viewHolder.imageView);
}
}
#Override
public int getItemCount() {
return jcontent.size()+1;
}
#Override
public int getItemViewType(int position) {
return (position == jcontent.size()) ? R.layout.button_card : R.layout.card_row;
}
public class ViewHolder extends RecyclerView.ViewHolder{
private TextView title,pages;
private ImageView imageView;
private Button buttonnext,buttonprev,go;
private CardView cardView;
private EditText editText;
public ViewHolder(final View view) {
super(view);
title = (TextView)view.findViewById(R.id.post_title);
imageView=(ImageView)view.findViewById(R.id.img);
buttonnext =(Button)view.findViewById(R.id.next);
buttonprev=(Button)view.findViewById(R.id.prev);
go=(Button)view.findViewById(R.id.go);
editText=(EditText)view.findViewById(R.id.et_go_page);
cardView=(CardView)view.findViewById(R.id.cvv);
pages=(TextView)view.findViewById(R.id.number_pages);
}
}
}
Your Fragment
public class maghalat extends Fragment {
private RecyclerView recyclerView;
private DataAdapter adapter;
private View myFragmentView;
private String TAG = MainActivity.class.getSimpleName();
private ProgressDialog pDialog;
private int numpage=0;
public int sag;
private String url = "http://memaraneha.ir/category/%d9%85%d9%82%d8%a7%d9%84%d8%a7%d8%aa/page/"+String.valueOf(sag)+"/?json=get_posts";
List<jsonContent> listcontent=new ArrayList<>();
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
myFragmentView = inflater.inflate(R.layout.maghalat, container, false);
if(isNetworkConnected()) {
asyncRun();
}else
{
Toast.makeText(getActivity().getApplicationContext(), "دستگاه شما به اینترنت متصل نیست!", Toast.LENGTH_LONG).show();
}
return myFragmentView;
}
public void asyncRun(){
new GetContacts().execute();
}
public class GetContacts extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
// Showing progress dialog
pDialog = new ProgressDialog(getActivity());
pDialog.setMessage("Please wait...");
pDialog.setCancelable(false);
pDialog.show();
}
#Override
protected Void doInBackground(Void... arg0) {
HttpHandler sh = new HttpHandler();
sag=numpage+1;
// Making a request to url and getting response
String jsonStr = sh.makeServiceCall(url);
Log.e(TAG, "Response from url: " + jsonStr);
if (jsonStr != null) {
try {
JSONObject jsonObj = new JSONObject(jsonStr);
int id=jsonObj.getInt("pages");
JSONArray posts = jsonObj.getJSONArray("posts");
for (int i = 0; i < posts.length(); i++) {
JSONObject c = posts.getJSONObject(i);
jsonContent jsonContent=new jsonContent();
jsonContent.title=c.getString("title");
//img
JSONObject post_img=c.getJSONObject("thumbnail_images");
for (int j=0;j<post_img.length();j++)
{
JSONObject v=post_img.getJSONObject("mom-portfolio-two");
jsonContent.imgurl=v.getString("url");
}
jsonContent.pages=id;
listcontent.add(jsonContent);
}
} catch (final JSONException e) {
Log.e(TAG, "Json parsing error: " + e.getMessage());
getActivity().runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(getActivity().getApplicationContext(),
"Json parsing error: " + e.getMessage(),
Toast.LENGTH_LONG)
.show();
}
});
}
} else {
Log.e(TAG, "Couldn't get json from server.");
getActivity().runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(getActivity().getApplicationContext(),
"Couldn't get json from server. Check LogCat for possible errors!",
Toast.LENGTH_LONG)
.show();
}
});
}
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
pDialog.dismiss();
recyclerView=(RecyclerView)myFragmentView.findViewById(R.id.recycler_view);
recyclerView.setHasFixedSize(true);
RecyclerView.LayoutManager layoutManager = new LinearLayoutManager(getActivity().getApplicationContext());
recyclerView.setLayoutManager(layoutManager);
adapter=new DataAdapter(getActivity(),listcontent,maghalat.this);
recyclerView.setAdapter(adapter);
}
}
private boolean isNetworkConnected() {
ConnectivityManager cm = (ConnectivityManager) getActivity().getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo ni = cm.getActiveNetworkInfo();
if (ni == null) {
// There are no active networks.
return false;
} else
return true;
}
}

Add Button Click Event in RecyclerView

UserAdapter.java :
public class UsersAdapter extends RecyclerView.Adapter<UsersAdapter.UsersViewHolder> {
private List<Users> usersList;
private ImageLoader imageLoader = AppController.getInstance().getImageLoader();
private Context mContext;
public class UsersViewHolder extends RecyclerView.ViewHolder {
public TextView txtUsername, txtCreatedAt;
public NetworkImageView imgUser;
public ImageButton btnMsg, btnDel;
public UsersViewHolder(View view) {
super(view);
txtUsername = (TextView) view.findViewById(R.id.txt_username);
txtCreatedAt = (TextView) view.findViewById(R.id.txt_created_at);
imgUser = (NetworkImageView) view.findViewById(R.id.img_user);
btnMsg = (ImageButton) view.findViewById(R.id.btn_msg);
btnDel = (ImageButton) view.findViewById(R.id.btn_delete);
}
}
public UsersAdapter(Context context, List<Users> usersList) {
mContext = context;
this.usersList = usersList;
}
#Override
public UsersViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View itemView = LayoutInflater.from(parent.getContext()).inflate(R.layout.users_list_row, parent, false);
return new UsersViewHolder(itemView);
}
#Override
public void onBindViewHolder(UsersViewHolder holder, int position) {
Users users = usersList.get(position);
holder.txtUsername.setText(users.getUserName() + " " + users.getUserSurname());
holder.txtCreatedAt.setText(users.getCreatedAt());
if (imageLoader == null)
imageLoader = AppController.getInstance().getImageLoader();
holder.imgUser.setImageUrl(users.getUserImgPath(), imageLoader);
holder.btnMsg.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(mContext, "Clicked", Toast.LENGTH_SHORT);
}
});
}
#Override
public int getItemCount() {
return usersList.size();
}
}
AppliersActivity :
public class AppliersActivity extends AppCompatActivity {
private static final String TAG = AppliersActivity.class.getSimpleName();
private SQLiteHandler db;
private SessionManager session;
private ProgressDialog pDialog;
private String uid, api_key, adId;
private List<Users> usersList = new ArrayList<>();
private RecyclerView recyclerView;
private UsersAdapter mAdapter;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_appliers);
definitions();
getAppliers();
}
private void definitions() {
adId = getIntent().getStringExtra("adId");
// Progress dialog
pDialog = new ProgressDialog(this);
pDialog.setCancelable(false);
// SqLite database handler
db = new SQLiteHandler(getApplicationContext());
// session manager
session = new SessionManager(getApplicationContext());
if (!session.isLoggedIn()) {
logoutUser();
}
// Fetching user details from sqlite
HashMap<String, String> user = db.getUserDetails();
uid = user.get("uid");
api_key = user.get("api_key");
recyclerView = (RecyclerView) findViewById(R.id.appliers_recycler_view);
mAdapter = new UsersAdapter(getApplicationContext(), usersList);
RecyclerView.LayoutManager mLayoutManager = new LinearLayoutManager(getApplicationContext());
recyclerView.setLayoutManager(mLayoutManager);
recyclerView.setItemAnimator(new DefaultItemAnimator());
recyclerView.addItemDecoration(new DividerItemDecoration(this, LinearLayoutManager.VERTICAL));
recyclerView.setAdapter(mAdapter);
recyclerView.addOnItemTouchListener(new RecyclerTouchListener(getApplicationContext(), recyclerView, new OnTouchActionListener() {
#Override
public void onLeftSwipe(View view, int position) {
}
#Override
public void onRightSwipe(View view, int position) {
}
#Override
public void onClick(View view, int position) {
String adId = usersList.get(position).getUserId();
}
}));
}
public static interface OnTouchActionListener {
public void onLeftSwipe(View view, int position);
public void onRightSwipe(View view, int position);
public void onClick(View view, int position);
}
public static class RecyclerTouchListener implements RecyclerView.OnItemTouchListener {
private OnTouchActionListener mOnTouchActionListener;
private GestureDetectorCompat mGestureDetector;
public RecyclerTouchListener(Context context, final RecyclerView recyclerView, OnTouchActionListener onTouchActionListener) {
mOnTouchActionListener = onTouchActionListener;
mGestureDetector = new GestureDetectorCompat(context,new GestureDetector.SimpleOnGestureListener(){
#Override
public boolean onSingleTapUp(MotionEvent e) {
return true;
}
#Override
public void onLongPress(MotionEvent e) {
}
});
}
#Override
public boolean onInterceptTouchEvent(RecyclerView rv, MotionEvent e) {
View child = rv.findChildViewUnder(e.getX(), e.getY());
if (child != null && mOnTouchActionListener != null && mGestureDetector.onTouchEvent(e)) {
mOnTouchActionListener.onClick(child, rv.getChildPosition(child));
}
return false;
}
#Override
public void onTouchEvent(RecyclerView rv, MotionEvent e) {
}
#Override
public void onRequestDisallowInterceptTouchEvent(boolean disallowIntercept) {
}
}
private void getAppliers() {
// Tag used to cancel the request
String tag_string_req = "req_appliers";
pDialog.setMessage("Lütfen Bekleyin...");
showDialog();
StringRequest strReq = new StringRequest(Request.Method.GET,
ApiRoutes.URL_JOB_APPLIERS+ "/" + adId, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.d(TAG, "Appliers Response: " + response.toString());
hideDialog();
try {
JSONObject jObj = new JSONObject(response);
boolean error = jObj.getBoolean("error");
// Check for error node in json
if (!error) {
usersList.clear();
mAdapter.notifyDataSetChanged();
JSONArray usersArray = jObj.getJSONArray("appliers");
Users users;
for (int i = 0; i < usersArray.length(); i++) {
JSONObject jsonobject = usersArray.getJSONObject(i);
users = new Users(jsonobject.getString("uid"), jsonobject.getString("name"), jsonobject.getString("surname"), ApiRoutes.FOLDER_IMG + "/" + jsonobject.getString("uid") + "/profile_img.png", jsonobject.getString("created_at"));
usersList.add(users);
}
mAdapter.notifyDataSetChanged();
} else {
String errorMsg = jObj.getString("error_msg");
Toast.makeText(getApplicationContext(),
errorMsg, Toast.LENGTH_LONG).show();
}
} catch (JSONException e) {
// JSON error
e.printStackTrace();
Toast.makeText(getApplicationContext(), "Json error: " + e.getMessage(), Toast.LENGTH_LONG).show();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e(TAG, "User Ads Error: " + error.getMessage());
Toast.makeText(getApplicationContext(),
error.getMessage(), Toast.LENGTH_LONG).show();
hideDialog();
}
}) {
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
HashMap<String, String> headers = new HashMap<>();
headers.put("Authorization", api_key);
return headers;
}
};
// Adding request to request queue
AppController.getInstance().addToRequestQueue(strReq, tag_string_req);
}
private void showDialog() {
if (!pDialog.isShowing())
pDialog.show();
}
private void hideDialog() {
if (pDialog.isShowing())
pDialog.dismiss();
}
/**
* Logging out the user. Will set isLoggedIn flag to false in shared
* preferences Clears the user data from sqlite users table
* */
private void logoutUser() {
session.setLogin(false);
db.deleteUsers();
// Launching the login activity
Intent intent = new Intent(this, LoginActivity.class);
startActivity(intent);
finish();
}
}
I have two imagebutton on recyclerviewer' s rows. I want to add click event for each row. I sent the applicationcontext to an adapter from activity. And i added to onclicklistener event in adapter class. But it does not show toast on the screen. How can i solve this problem ?
You don't call show() method of Toast in your adapter class.
Change it as following
holder.btnMsg.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(mContext, "Clicked", Toast.LENGTH_SHORT).show();
}
});

Contexts of Fragments

I'm working on an amusement park record information in which I have made a recyclerview that loads data from a MySQL database. Recyclerview is contained in a Fragment. Following is my mainactivity code:
public class TicketSoldFragment extends Fragment {
Button press;
String url="http://10.0.2.2/data/ticketsold_show_swing.php";
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView=inflater.inflate(R.layout.fragment_ticketsold,container,false);
return rootView;
}
#Override
public void onViewCreated(View view, Bundle savedInstanceState) {
final RecyclerView rv=(RecyclerView)view.findViewById(R.id.recyclerview_ticketsold);
rv.setLayoutManager(new LinearLayoutManager(getContext()));
rv.setItemAnimator(new DefaultItemAnimator());
Context c=getActivity().getApplicationContext();
press=(Button)view.findViewById(R.id.buttonplease);
press.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Downloader d=new Downloader(getActivity().getApplicationContext(),url,rv);
d.execute();
}
});
}
}
This is my Downloader Code:
public class Downloader extends AsyncTask<Void,Integer,String> {
Context c;
String stringURL;
RecyclerView rv;
ProgressDialog pd;
public Downloader(Context c, String stringURL, RecyclerView rv) {
this.c= c;
this.stringURL = stringURL;
this.rv = rv;
}
#Override
protected String doInBackground(Void... params) {
String data=this.downloadData();
return data;
}
#Override
protected void onPostExecute(String data) {
super.onPostExecute(data);
pd.dismiss();
if(data!=null) {
Parser p=new Parser(c,data,rv);
p.execute();
}
else {
Toast.makeText(c,"Unable to download",Toast.LENGTH_SHORT).show();
}
}
private String downloadData() {
InputStream is=null;
String line=null;
try {
URL url=new URL(stringURL);
HttpURLConnection con= (HttpURLConnection) url.openConnection();
is=new BufferedInputStream(con.getInputStream());
BufferedReader br=new BufferedReader(new InputStreamReader(is));
StringBuffer sb=new StringBuffer();
if(br!=null) {
while((line=br.readLine())!=null) {
sb.append(line+"\n");
}
}
else {
return null;
}
return sb.toString();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
finally {
if(is!=null) {
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return null;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
pd=new ProgressDialog(c);
pd.setTitle("Download Data");
pd.setMessage("Downloading...Please Wait!");
pd.show();
}
}
This is my Parser:
public class Parser extends AsyncTask<Void,Integer,Integer> {
Context c;
String data;
RecyclerView rv;
ProgressDialog pd;
ArrayList<String> swings=new ArrayList<>();
MyAdapter adapter;
public Parser(Context c, String data, RecyclerView rv) {
this.c = c;
this.data = data;
this.rv = rv;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
pd=new ProgressDialog(c);
pd.setTitle("Parse Data");
pd.setMessage("Parsing...Please wait!");
pd.show();
}
#Override
protected Integer doInBackground(Void... params) {
return this.parse();
}
#Override
protected void onPostExecute(Integer integer) {
super.onPostExecute(integer);
pd.dismiss();
if(integer==1) {
adapter=new MyAdapter(c,swings);
rv.setAdapter(adapter );
}
else {
Toast.makeText(c,"Unable to parse data",Toast.LENGTH_SHORT).show();
}
}
private int parse() {
try {
JSONArray ja=new JSONArray(data);
JSONObject jo=null;
swings.clear();
for(int i=0;i<ja.length();i++) {
jo=ja.getJSONObject(i);
String name=jo.getString("name");
swings.add(name);
}
return 1;
} catch (JSONException e) {
e.printStackTrace();
}
return 0;
}
}
now problem is when im sending Fragment context from TicketSoldFragment to Downloader constructor, there is an error and i cant figure it out.
this is my Adapter:
public class MyAdapter extends RecyclerView.Adapter<MyHolder> {
Context c;
ArrayList<String> swings;
public MyAdapter(Context c,ArrayList<String>swings){
this.c=c;
this.swings=swings;
}
#Override
public MyHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View v= LayoutInflater.from(parent.getContext()).inflate(R.layout.card_ticketsold,parent,false);
MyHolder holder=new MyHolder(v);
return holder;
}
#Override
public void onBindViewHolder(MyHolder holder, int position) {
holder.nameTxt.setText(swings.get(position));
holder.setItemClickListener(new ItemClickListener() {
#Override
public void onItemClick(int pos) {
Toast.makeText(c,swings.get(pos),Toast.LENGTH_SHORT).show();
}
});
}
#Override
public int getItemCount() {
return swings.size();
}
}
and my holder:
public class MyHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
TextView nameTxt;
ItemClickListener itemClickListener;
public MyHolder(View itemView) {
super(itemView);
nameTxt= (TextView) itemView.findViewById(R.id.swing_name_ticket_sold_text);
itemView.setOnClickListener(this);
}
public void setItemClickListener(ItemClickListener ic)
{
this.itemClickListener=ic;
}
#Override
public void onClick(View v) {
this.itemClickListener.onItemClick(getLayoutPosition());
}
}
without knowing the error you get I can assume it is related to the getApplicationContext() - getActivity() is the right context, so it should be
Downloader d = new Downloader(getActivity(), url, rv);
The Application Context can be used for Data Access but not for UI and you are doing this in your code.

Not receiving data from MySQL database to Android Recyclerview

I'm working on an amusement park record application that receives data from MySQL database and displays on recyclerview in android but im unable to download it from database.
This is my Adapter
public class MyAdapter extends RecyclerView.Adapter<MyHolder> {
Context c;
ArrayList<String> swing;
public MyAdapter(Context c,ArrayList<String>swing){
this.c=c;
this.swing=swing;
}
#Override
public MyHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View v= LayoutInflater.from(parent.getContext()).inflate(R.layout.card_ticketsold,parent,false);
MyHolder holder=new MyHolder(v);
return holder;
}
#Override
public void onBindViewHolder(MyHolder holder, int position) {
holder.nameTxt.setText(swing.get(position));
holder.setItemClickListener(new ItemClickListener() {
#Override
public void onItemClick(int pos) {
Toast.makeText(c,swing.get(pos),Toast.LENGTH_SHORT).show();
}
});
}
#Override
public int getItemCount() {
return swing.size();
}
}
this is my holder:
public class MyHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
TextView nameTxt;
ItemClickListener itemClickListener;
public MyHolder(View itemView) {
super(itemView);
nameTxt= (TextView) itemView.findViewById(R.id.swing_name_ticket_sold_text);
itemView.setOnClickListener(this);
}
public void setItemClickListener(ItemClickListener ic)
{
this.itemClickListener=ic;
}
#Override
public void onClick(View v) {
this.itemClickListener.onItemClick(getLayoutPosition());
}
}
This is the fragment containing the recyclerview:
public class TicketSoldFragment extends Fragment {
Button press;
String url="http:// 10.0.2.2/data/ticketsold_show_swing.php";
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView=inflater.inflate(R.layout.fragment_ticketsold,container,false);
return rootView;
}
#Override
public void onViewCreated(View view, Bundle savedInstanceState) {
final RecyclerView rv=(RecyclerView)view.findViewById(R.id.recyclerview_ticketsold);
rv.setLayoutManager(new LinearLayoutManager(getContext()));
rv.setItemAnimator(new DefaultItemAnimator());
Context c=getActivity().getApplicationContext();
press=(Button)view.findViewById(R.id.buttonplease);
press.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Downloader d=new Downloader(getActivity(),url,rv);
d.execute();
}
});
}
}
this is downloader:
public class Downloader extends AsyncTask<Void,Integer,String> {
Context c;
String stringURL;
RecyclerView rv;
ProgressDialog pd;
public Downloader(Context c, String stringURL, RecyclerView rv) {
this.c= c;
this.stringURL = stringURL;
this.rv = rv;
}
#Override
protected String doInBackground(Void... params) {
String data=this.downloadData();
return data;
}
#Override
protected void onPostExecute(String data) {
super.onPostExecute(data);
pd.dismiss();
if(data!=null)
{
Parser p=new Parser(c,data,rv);
p.execute();
}
else {
Toast.makeText(c,"Unable to download",Toast.LENGTH_SHORT).show();
}
}
private String downloadData()
{
InputStream is=null;
String line=null;
try
{
URL url=new URL(stringURL);
HttpURLConnection con= (HttpURLConnection) url.openConnection();
is=new BufferedInputStream(con.getInputStream());
BufferedReader br=new BufferedReader(new InputStreamReader(is));
StringBuffer sb=new StringBuffer();
if(br!=null)
{
while((line=br.readLine())!=null){
sb.append(line+"\n");
}
}
else {
return null;
}
return sb.toString();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
finally {
if(is!=null)
{
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return null;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
pd=new ProgressDialog(c);
pd.setTitle("Download Data");
pd.setMessage("Downloading...Please Wait!");
pd.show();
}
}
and Parser:
public class Parser extends AsyncTask<Void,Integer,Integer> {
Context c;
String data;
RecyclerView rv;
ProgressDialog pd;
ArrayList<String> swings=new ArrayList<>();
MyAdapter adapter;
public Parser(Context c, String data, RecyclerView rv) {
this.c = c;
this.data = data;
this.rv = rv;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
pd=new ProgressDialog(c);
pd.setTitle("Parse Data");
pd.setMessage("Parsing...Please wait!");
pd.show();
}
#Override
protected Integer doInBackground(Void... params) {
return this.parse();
}
#Override
protected void onPostExecute(Integer integer) {
super.onPostExecute(integer);
pd.dismiss();
if(integer==1)
{
adapter=new MyAdapter(c,swings);
rv.setAdapter(adapter );
}
else
{
Toast.makeText(c,"Unable to parse data",Toast.LENGTH_SHORT).show();
}
}
private int parse()
{
try{
JSONArray ja=new JSONArray(data);
JSONObject jo=null;
swings.clear();
for(int i=0;i<ja.length();i++)
{
jo=ja.getJSONObject(i);
String name=jo.getString("name");
swings.add(name);
}
return 1;
} catch (JSONException e) {
e.printStackTrace();
}
return 0;
}
}
when i run this, the Toast "Unable to download" appears...so my data is not downloaded at all! and there is an error in logcat "no network" and sendUserActionEvent() mView == null

Image from clicked item of Recyclerview

I am new to Android app development. I am trying to display the image and text in another Activity from the item of the Recyclerview which was clicked by the user. I am getting unreachable statement error. Please help me out!
Here's my code for getting image:
imgUrl = new getDataAsyncTask().getImageUrl(recyclerView.getChildPosition(child));
and the full Activity code:
public class RestaurantsAndCafesActivity extends Activity {
public static final String URL = "http://192.168.8.101:80/jay.html";
private RecyclerView mRecyclerView;
private RCRecyclerAdapter adapter;
public String imgUrl;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.reyclerview_layout);
/* Initialize RecyclerView */
mRecyclerView = (RecyclerView) findViewById(R.id.recycler_view);
mRecyclerView.setLayoutManager(new LinearLayoutManager(this));
//parseResult();
new getDataAsyncTask().execute();
final GestureDetector mGestureDetector = new GestureDetector(RestaurantsAndCafesActivity.this, new GestureDetector.SimpleOnGestureListener() {
#Override public boolean onSingleTapUp(MotionEvent e) {
return true;
}
});
mRecyclerView.addOnItemTouchListener(new RecyclerView.OnItemTouchListener() {
#Override
public boolean onInterceptTouchEvent(RecyclerView recyclerView, MotionEvent motionEvent) {
View child = recyclerView.findChildViewUnder(motionEvent.getX(),motionEvent.getY());
if(child!=null && mGestureDetector.onTouchEvent(motionEvent)){
Toast.makeText(RestaurantsAndCafesActivity.this,"Clicked Number "+recyclerView.getChildPosition(child), Toast.LENGTH_SHORT).show();
return true;
imgUrl = new getDataAsyncTask().getImageUrl(recyclerView.getChildPosition(child));
}
return false;
}
#Override
public void onTouchEvent(RecyclerView recyclerView, MotionEvent motionEvent) {
}
});
}
public class getDataAsyncTask extends AsyncTask<Void,Void,Void>{
ArrayList<FeedItem> arrayList = new ArrayList<>();
public String getImageUrl(int pos)
{
return arrayList.get(pos).thumb;
}
#Override
protected Void doInBackground(Void... params) {
try {
org.jsoup.nodes.Document document = Jsoup.connect(URL).get();
for(Element e : document.select("img[src]"))
{
Elements imgScr = e.select("img[src]");
String elements = imgScr.attr("src");
String text = imgScr.attr("alt");
String desc = imgScr.attr("title");
arrayList.add(new FeedItem(text, elements, desc));
}
}
catch(IOException e)
{
e.printStackTrace();
}
return null;
}
ProgressDialog progressDialog;
#Override
protected void onPreExecute()
{
progressDialog = ProgressDialog.show(RestaurantsAndCafesActivity.this,"Loading","Please Wait",true,false);
}
#Override
protected void onPostExecute(Void aVoid) {
progressDialog.dismiss();
adapter = new RCRecyclerAdapter(getApplicationContext(),arrayList);
mRecyclerView.setAdapter(adapter);
}
}
}
I just want to get the image url so that I can send it to another Activity via Intent.putExtra method. Please tell me where I am going wrong, or is there any other way for what I am trying to achieve?
In your onInterceptTouchEvent the
imgUrl = new getDataAsyncTask().getImageUrl(recyclerView.getChildPosition(child)); needs to be before return true. It's declared after return true; which makes the statement unreachable.

Categories

Resources