Android Post values from Recyclerview Checkbox to database - java

I'm working on an employee attendance attendance applicaion, for that I'm listing employee namelist from my MySQL database to android RecyclerView. Everything is working fine. But what I actually wanted is, I want to update my attendance table with the CheckBox values, my table contains 3 columns id,emp_id,emp_attn, If the checkbox is checked for an employee, the app should post it as checked ! So how can i identify each checkbox in my recyclerview,
MyAdapter.java
import android.content.Context;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;
import java.util.List;
/**
* Created by Akshay N Shaju on 10/20/2017.
*/
public class MyAdapter extends RecyclerView.Adapter<MyAdapter.ViewHolder>{
private List<Listitems> listitemses;
private Context context;
public MyAdapter(List<Listitems> listitemses, Context context) {
this.listitemses = listitemses;
this.context = context;
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View v = LayoutInflater.from(parent.getContext())
.inflate(R.layout.list_item, parent, false);
return new ViewHolder(v);
}
#Override
public void onBindViewHolder(ViewHolder holder, int position) {
final Listitems listitem = listitemses.get(position);
holder.CbHead.setText(listitem.getHead());
holder.textViewDesc.setText(listitem.getDesc());
holder.CbHead.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(context,listitem.getHead(), Toast.LENGTH_LONG).show();
}
});
}
#Override
public int getItemCount() {
return listitemses.size();
}
public class ViewHolder extends RecyclerView.ViewHolder {
public CheckBox CbHead;
public TextView textViewDesc;
public LinearLayout linearLayout;
public ViewHolder(View itemView) {
super(itemView);
CbHead = (CheckBox) itemView.findViewById(R.id.CbHead);
textViewDesc = (TextView) itemView.findViewById(R.id.textViewDisc);
linearLayout = (LinearLayout) itemView.findViewById(R.id.LinearLyout1);
}
}
}
MainActivity.java
import android.app.ProgressDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.widget.Toast;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.lang.ref.ReferenceQueue;
import java.util.ArrayList;
import java.util.List;
public class MainActivity extends AppCompatActivity {
private static final String URL_DATA = "https://xxxxxxx.com/sample.json";
private RecyclerView recyclerView;
private RecyclerView.Adapter adapter;
private List<Listitems> listitemses;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
recyclerView = (RecyclerView) findViewById(R.id.recyclerView);
recyclerView.setHasFixedSize(true);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
listitemses = new ArrayList<>();
loadRecyclerViewData();
}
private void loadRecyclerViewData(){
final ProgressDialog progressDialog = new ProgressDialog(this);
progressDialog.setMessage("Loading Data");
progressDialog.show();
StringRequest stringRequest = new StringRequest(Request.Method.GET,
URL_DATA,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
progressDialog.dismiss();
try {
JSONObject jsonObject = new JSONObject(response);
JSONArray array = jsonObject.getJSONArray("employee");
for(int i=0; i<array.length(); i++){
JSONObject o = array.getJSONObject(i);
Listitems item = new Listitems(
o.getString("name"),
o.getString("id"),
o.getString("image")
);
listitemses.add(item);
}
adapter = new MyAdapter(listitemses,getApplicationContext());
recyclerView.setAdapter(adapter);
} catch (JSONException e) {
e.printStackTrace();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
progressDialog.dismiss();
Toast.makeText(getApplicationContext(),"error",Toast.LENGTH_SHORT).show();
}
});
RequestQueue requestQueue = Volley.newRequestQueue(this);
requestQueue.add(stringRequest);
}
}
ListItems.java
/**
* Created by Akshay N Shaju on 10/20/2017.
*/
public class Listitems {
private String head;
private String desc;
private String imageurl;
public Listitems(String head, String desc, String imageurl) {
this.head = head;
this.desc = desc;
this.imageurl = imageurl;
}
public String getHead() {
return head;
}
public String getDesc() {
return desc;
}
public String getImageurl() {
return imageurl;
}
}
Here in my adapter I tried an onClick Listner, which toast the employee name when checked and it worked ! but how can I get all the checkbox status and post it to my database table when save button clicked.

Store the state in your ListItem, whenever the state of the CheckBox changes:
public class Listitems {
...
public bool isChecked;
...
}
Instead of onClick, listen to the state change instead:
holder.CbHead.setOnCheckedChangeListener(new OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
listitem.isChecked = isChecked
}
});
Finally when binding, make sure to reflect the checked state of the CheckBox:
holder.CbHead.setText(listitem.getHead());
holder.CbHead.setChecked(listitem.isChecked)
You are using a recycler view so while the CheckBox is still on screen it will hold your "checked" state. However once it scrolls off screen, it will be recycled. Hence you need to store the state somewhere, your own ListItem is the best bet

Related

SharedPreferences Data spreads on every Fragment

I got a problem with the date of my SharedPreferences. I am using 5 Fragment wher you can dynamically add item to a RecyclerView. The Problem is that when ever I save my data on a particular fragment and reload the app the value that has been saved loads into every single Fragment of mine.It actually save the data to the Fragment it is on.I am using Gson to save my ArrayList of items
This is my Fragment (Fragment0 from 5 in total, the others are just copied and refactored)
package com.example.barryblack;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.ItemTouchHelper;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import java.lang.reflect.Type;
import java.util.ArrayList;
import static android.content.Context.MODE_PRIVATE;
public class FragmentPage0 extends Fragment {
private ExampleAdapter mAdapter;
private EditText editTask;
ArrayList<MyItem> items;
private Button insertbtn;
private Button stateButton;
private TextView taskText;
private String task;
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable
Bundle savedInstanceState) {
CreateExampleList();
View view = inflater.inflate(R.layout.page_fragment0, container, false);
loadData();
RecyclerView recyclerView = view.findViewById(R.id.listRecyclerView);
recyclerView.setHasFixedSize(true);
RecyclerView.LayoutManager layoutManager = new LinearLayoutManager(getActivity());
new ItemTouchHelper(itemTouchHelperCallback).attachToRecyclerView(recyclerView);
recyclerView.setLayoutManager(layoutManager);
recyclerView.setItemViewCacheSize(500);
mAdapter = new ExampleAdapter(items);
recyclerView.setAdapter(mAdapter);
taskText = view.findViewById(R.id.tv_country);
insertbtn = view.findViewById(R.id.button_insert);
editTask = view.findViewById(R.id.editTask);
stateButton = view.findViewById(R.id.tv_button);
insertbtn.setEnabled(false);
editTask.addTextChangedListener(new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
String taskInput = editTask.getText().toString().trim();
insertbtn.setEnabled(!taskInput.isEmpty());
}
#Override
public void afterTextChanged(Editable s) {
task = editTask.getText().toString().trim();
}
});
insertbtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
InsertItem();
SaveData();
editTask.setText(null);
}
});
return view;
}
private void SaveData() {
SharedPreferences sharedPreferences = this.getActivity().getSharedPreferences("shared
preferences", MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
Gson gson = new Gson();
String json = gson.toJson(items);
editor.putString("task list", json);
editor.apply();
}
private void loadData() {
SharedPreferences sharedPreferences = this.getActivity().getSharedPreferences("shared
preferences", MODE_PRIVATE);
Gson gson = new Gson();
String json = sharedPreferences.getString("task list", null);
Type type = new TypeToken<ArrayList<MyItem>>() {
}.getType();
items = gson.fromJson(json, type);
if (items == null) {
items = new ArrayList();
}
}
public void InsertItem() {
items.add(new MyItem(task, stateButton));
mAdapter.notifyItemInserted(items.size());
}
private void CreateExampleList() {
items = new ArrayList<MyItem>();
}
ItemTouchHelper.SimpleCallback itemTouchHelperCallback = new ItemTouchHelper.SimpleCallback(0,
ItemTouchHelper.LEFT | ItemTouchHelper.RIGHT) {
#Override
public boolean onMove(#NonNull RecyclerView recyclerView, #NonNull RecyclerView.ViewHolder
viewHolder, #NonNull RecyclerView.ViewHolder target) {
return false;
}
#Override
public void onSwiped(#NonNull RecyclerView.ViewHolder viewHolder, int direction) {
items.remove(viewHolder.getAdapterPosition());
mAdapter.notifyItemRemoved(viewHolder.getAdapterPosition());
SaveData();
}
};
}
This is my Adapter. I think the problem is inside the OnCreateViewHolder but im not quiet sure
package com.example.barryblack;
import android.content.Context;
import android.content.SharedPreferences;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import androidx.recyclerview.widget.RecyclerView;
import java.util.ArrayList;
public class ExampleAdapter extends RecyclerView.Adapter<ExampleAdapter.ExampleViewHolder> {
private ArrayList<MyItem> mExampleList;
public static class ExampleViewHolder extends RecyclerView.ViewHolder {
public TextView mTextView;
private EditText topicName;
public Button mButton;
private int clicks = 1;
public static final String SHARED_PREFS = "sharedPrefs";
public static final String TOPIC = "topic";
public static final String CLICKS = "clicks";
public ExampleViewHolder(View itemView) {
super(itemView);
mTextView = itemView.findViewById(R.id.tv_country);
mButton = itemView.findViewById(R.id.tv_button);
topicName = itemView.findViewById(R.id.editText);
mButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
clicks++;
if (clicks % 2 == 0) {
mButton.setBackgroundResource(R.drawable.button_green);
}else
mButton.setBackgroundResource(R.drawable.button_red);
}
});
}
}
public ExampleAdapter(ArrayList<MyItem> exampleList) {
mExampleList = exampleList;
}
#Override
public ExampleViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View v = LayoutInflater.from(parent.getContext())
.inflate(R.layout.example_item, parent, false);
ExampleViewHolder evh = new ExampleViewHolder(v);
return evh;
}
#Override
public void onBindViewHolder(ExampleViewHolder holder, int position) {
MyItem currentItem = mExampleList.get(position);
holder.mTextView.setText(currentItem.getTaskText());
}
#Override
public int getItemCount() {
return mExampleList.size();
}
}
Use this for your fragments. So every fragment has his own SharedPreferences
private static final String SHARED_PREFS_FRAGMENT_A = "fragmentA";
private static final String SHARED_PREFS_FRAGMENT_B = "fragmentB";
...
SharedPreferences sharedPreferences = getActivity().getSharedPreferences(SHARED_PREFS_FRAGMENT_A , MODE_PRIVATE);

problem in open another activity from a custom adapter in java

I need to open another activity from a custom adapter, just like a list and then when I click on that, it will take to another activity and get a data from database and show it in the text view,
the problem is in SearchAdapter.java in the context.startActivity(intent);
here's my searchAdapter.java
package Adapter;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import android.widget.Toast;
//import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import com.example.manualdiagnosiskeperawatan.R;
import com.example.manualdiagnosiskeperawatan.isiDiagnosis;
import java.util.List;
import Model.Daftar;
class SearchViewHolder extends RecyclerView.ViewHolder{
public TextView judul, diagnosis;
public SearchViewHolder(View itemView) {
super(itemView);
judul = itemView.findViewById(R.id.judul);
diagnosis = itemView.findViewById(R.id.textViewIsi);
}
}
public class SearchAdapter extends RecyclerView.Adapter<SearchViewHolder>
{
private Context context;
private List<Daftar> data;
public SearchAdapter(Context context, List<Daftar> data) {
this.context = context;
this.data = data;
}
#Override
public SearchViewHolder onCreateViewHolder( ViewGroup parent, int viewType) {
LayoutInflater inflater = LayoutInflater.from(parent.getContext());
View itemView = inflater.inflate(R.layout.layout_item,parent,false);
return new SearchViewHolder(itemView);
}
#Override
public void onBindViewHolder(final SearchViewHolder holder, final int position)
{
holder.judul.setText(data.get(position).getJudul());
//open activity
holder.itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Toast.makeText(context, data.get(position).getDiagnosis(),Toast.LENGTH_SHORT).show();
//this code, isn't working
Intent intent = new Intent(context, isiDiagnosis.class);
intent.putExtra("did",data.get(position).getDid());
context.startActivity(intent);
}
});
}
#Override
public int getItemCount() {
return data.size();
}
}
and here is my isiDiagnosis.java which will be opened when I clicked the list from the SearchAdapter.java
package com.example.manualdiagnosiskeperawatan;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.RecyclerView;
import android.content.Intent;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.widget.TextView;
import com.mancj.materialsearchbar.MaterialSearchBar;
import org.w3c.dom.Text;
import java.util.ArrayList;
import java.util.List;
import Adapter.SearchAdapter;
import Database.Database;
import Model.Daftar;
public class isiDiagnosis extends AppCompatActivity {
RecyclerView recyclerView;
RecyclerView.LayoutManager layoutManager;
SearchAdapter adapter;
Database database;
List<Daftar> daftars = new ArrayList<>();
private TextView judul, diagnosis;
private String DID = "judul";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_isi_diagnosis);
DID = getIntent().getStringExtra("judul");
database = new Database(this);
diagnosis = (TextView) findViewById(R.id.textViewIsi);
//init DB
loadData(DID);
}
private void loadData(String did) {
//i don't really know how to code, just see from the youtube, so i made this myself
// database.getDiagnosis();
// String diagnosis = daftars.get(database.getDiagnosis());
// database.getDiagnosis(diagnosis.setText());
}
}
here's my searchDiagnosis.java
package com.example.manualdiagnosiskeperawatan;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.widget.ListViewCompat;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.widget.Adapter;
import android.widget.ListView;
import com.mancj.materialsearchbar.MaterialSearchBar;
import java.util.ArrayList;
import java.util.List;
import Adapter.SearchAdapter;
import Database.Database;
public class searchDiagnosis extends AppCompatActivity {
RecyclerView recyclerView;
RecyclerView.LayoutManager layoutManager;
SearchAdapter adapter;
Database database;
MaterialSearchBar materialSearchBar;
List<String> suggestList = new ArrayList<>();
#Override
protected void onStart() {
super.onStart();
adapter = new SearchAdapter(getBaseContext(),database.getDaftar());
recyclerView.setAdapter(adapter);
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_search_diagnosis);
//init view
recyclerView = (RecyclerView) findViewById(R.id.recycler_search);
layoutManager = new LinearLayoutManager(this);
recyclerView.setLayoutManager(layoutManager);
recyclerView.setHasFixedSize(true);
materialSearchBar =(MaterialSearchBar) findViewById(R.id.search_bar);
//init DB
database = new Database(this);
//Setup search bar
materialSearchBar.setHint("Search");
materialSearchBar.setCardViewElevation(10);
loadSuggestList();
materialSearchBar.addTextChangeListener(new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
List<String> suggest = new ArrayList<>();
for(String search:suggestList){
if(search.toLowerCase().contains(materialSearchBar.getText().toLowerCase()))
suggest.add(search);
}
materialSearchBar.setLastSuggestions(suggest);
}
#Override
public void afterTextChanged(Editable s) {
}
});
materialSearchBar.setOnSearchActionListener(new MaterialSearchBar.OnSearchActionListener() {
#Override
public void onSearchStateChanged(boolean enabled) {
if(!enabled) {
// recyclerView.setAdapter(adapter);
//if close Search, just restore default
adapter = new SearchAdapter(getBaseContext(),database.getDaftar());
recyclerView.setAdapter(adapter);
}
}
#Override
public void onSearchConfirmed(CharSequence text) {
startSearch(text.toString());
}
#Override
public void onButtonClicked(int buttonCode) {
}
});
//Init adapter default set all result
adapter = new SearchAdapter(this,database.getDaftar());
}
private void startSearch(String text) {
adapter = new SearchAdapter(this,database.getDataByJudul(text));
recyclerView.setAdapter(adapter);
}
private void loadSuggestList() {
suggestList = database.getJudul();
materialSearchBar.setLastSuggestions(suggestList);
}
}
here's my Daftar.class
package Model;
public class Daftar {
public int id;
public String did, judul, diagnosis;
public Daftar(int id,String did, String judul, String diagnosis) {
this.id = id;
this.did = did;
this.judul = judul;
this.diagnosis = diagnosis;
}
public Daftar() {
}
public int getId() {
return id;
}
public String getDid() {
return did;
}
public void setDid(String did) {
this.did = did;
}
public void setId(int id) {
this.id = id;
}
public String getJudul() {
return judul;
}
public void setJudul(String judul) {
this.judul = judul;
}
public String getDiagnosis() {
return diagnosis;
}
public void setDiagnosis(String diagnosis) {
this.diagnosis = diagnosis;
}
}
Look I don't know what kind of database is this, but I know that you are not receiving the intent extra correctly:
In your isiDiagnosis:
............
//get the did like this
DID = getIntent().getStringExtra("did");
.......
loadData(DID);
//loading the data is up to you according to the database
private void loadData(String did) {.........}

how can i save " PDF " file in RecylerView?

I am creating an offline application for schoolchildren. In this project, a schoolboy clicking a "RecylerView" to upload a book "Pdf" and save it to an external storage. my problem is that it can only view a book using the Internet. If you turn off the Internet, it's simple not to see the pdf file.
please help
implementation 'com.github.kk121:File-Loader:1.1'
implementation 'com.karumi:dexter:5.0.0'
My Main Activity
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.RelativeLayout;
import java.util.ArrayList;
import java.util.List;
> public class MainActivity extends AppCompatActivity {
List<Product> productList;
//the recyclerview
RecyclerView recyclerView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Animation animation = AnimationUtils.loadAnimation(this, R.anim.anim_about_card_show);
RelativeLayout relativeLayout = findViewById(R.id.rl);
relativeLayout.startAnimation(animation);
//getting the recyclerview from xml
recyclerView = (RecyclerView) findViewById(R.id.recyclerView);
recyclerView.setHasFixedSize(true);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
//initializing the productlist
productList = new ArrayList<>();
//adding some items to our list
productList.add(
new Product(
1,
"TEst 11111 \n",
60000,
R.drawable.android,
"link1"
));
productList.add(
new Product(
1,
" More types, Methods, Conditionals \n",
60000,
R.drawable.android,
"link2"
));
productList.add(
new Product(
1,
"Loops, Arrays ",
60000,
R.drawable.android,
"lin3"
));
productList.add(
new Product(
1,
"Strings",
60000,
R.drawable.android,
"https://firebasestorage.googleapis.com/v0/b/firepdf-4c1d6.appspot.com/o/2.intro.pdf?alt=media&token=75731b04-c1e7-42c4-b988-e50a8f7e5f6b "
));
//creating recyclerview adapter
ProductAdapter adapter = new ProductAdapter(this, productList);
//setting adapter to recyclerview
recyclerView.setAdapter(adapter);
}
}
Adapter
import android.app.DownloadManager;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.support.v7.widget.CardView;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import java.util.List;
> public class ProductAdapter extends RecyclerView.Adapter<ProductAdapter.ProductViewHolder> {
//this context we will use to inflate the layout
private Context mCtx;
//we are storing all the products in a list
private List<Product> productList;
//getting the context and product list with constructor
public ProductAdapter(Context mCtx, List<Product> productList) {
this.mCtx = mCtx;
this.productList = productList;
}
#Override
public ProductViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
//inflating and returning our view holder
LayoutInflater inflater = LayoutInflater.from(mCtx);
View view = inflater.inflate(R.layout.layout_products, null);
return new ProductViewHolder(view);
}
#Override
public void onBindViewHolder(ProductViewHolder holder, final int position) {
//getting the product of the specified position
final Product product = productList.get(position);
//binding the data with the viewholder views
holder.textViewTitle.setText(product.getTitle());
holder.imageView.setImageDrawable(mCtx.getResources().getDrawable(product.getImage()));
holder.cardView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent i = new Intent(v.getContext(), pdf.class);
i.putExtra("title",productList.get(position).getTitle());
i.putExtra("product",productList.get(position).getTitle());
i.putExtra("link",productList.get(position).getLink());
mCtx.startActivity(i);
}
});
}
#Override
public int getItemCount() {
return productList.size();
}
class ProductViewHolder extends RecyclerView.ViewHolder {
TextView textViewTitle;
ImageView imageView;
CardView cardView;
public ProductViewHolder(View itemView) {
super(itemView);
cardView = itemView.findViewById(R.id.cardview);// card intial
textViewTitle = itemView.findViewById(R.id.textViewTitle);
imageView = itemView.findViewById(R.id.imageView);
}
}
}
My Pdf Viewer
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.MenuItem;
import android.widget.Toast;
import com.github.barteksc.pdfviewer.PDFView;
import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
public class pdf extends AppCompatActivity {
String link="",productList="",product="";
PDFView pdfView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_pdf);
product =getIntent().getStringExtra("title");
productList=getIntent().getStringExtra("productList");
link=getIntent().getStringExtra("link");
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setDisplayShowHomeEnabled(true);
getSupportActionBar().setTitle(productList);
pdfView=findViewById(R.id.pdfv);
//pdfView.fromAsset(link).load();
if (isConnected()) {
Toast.makeText(getApplicationContext(), "Internet Connected", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(getApplicationContext(), "No Internet Connection", Toast.LENGTH_SHORT).show();
AlertDialog.Builder builder = new AlertDialog.Builder(pdf.this);
builder.setTitle("NoInternet Connection Alert")
.setMessage("GO to Setting ?")
.setCancelable(false)
.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
startActivity(new Intent(android.provider.Settings.ACTION_WIRELESS_SETTINGS));
}
})
.setNegativeButton("No", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
Toast.makeText(pdf.this,"Go Back TO HomePage!",Toast.LENGTH_SHORT).show();
}
});
//Creating dialog box
AlertDialog dialog = builder.create();
dialog.show();
}
Bundle bundle = getIntent().getExtras();
if (bundle != null) {
link = getIntent().getStringExtra("link");
}
new pdf.RetrievePDFStream().execute(link);
}
public boolean isConnected() {
boolean connected = false;
try {
ConnectivityManager cm = (ConnectivityManager)getApplicationContext().getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo nInfo = cm.getActiveNetworkInfo();
connected = nInfo != null && nInfo.isAvailable() && nInfo.isConnected();
return connected;
} catch (Exception e) {
Log.e("Connectivity Exception", e.getMessage());
}
return connected;
}
class RetrievePDFStream extends AsyncTask<String, Void, InputStream> {
ProgressDialog progressDialog;
protected void onPreExecute()
{
progressDialog = new ProgressDialog(pdf.this);
progressDialog.setTitle("getting the book content...");
progressDialog.setMessage("Please wait...");
progressDialog.setCanceledOnTouchOutside(false);
progressDialog.show();
}
#Override
protected InputStream doInBackground(String... strings) {
InputStream inputStream = null;
try {
URL urlx = new URL(strings[0]);
HttpURLConnection urlConnection = (HttpURLConnection) urlx.openConnection();
if (urlConnection.getResponseCode() == 200) {
inputStream = new BufferedInputStream(urlConnection.getInputStream());
}
} catch (IOException e) {
return null;
}
return inputStream;
}
#Override
protected void onPostExecute(InputStream inputStream) {
pdfView.fromStream(inputStream).load();
progressDialog.dismiss();
}
}
#Override public boolean onOptionsItemSelected(MenuItem item)
{
if (item.getItemId() == android.R.id.home)//means home default hai kya yesok
{
onBackPressed();
return true;
}
return false;
}
}
And LAst Product
public class Product {
private int id;
private String title;
private int image;
private String link;
public Product(int id, String title, double price, int image, String link) {
this.id = id;
this.title = title;
this.image = image;
this.link=link;
}
public int getId() {
return id;
}
public String getTitle() {
return title;
}
public int getImage() {
return image;
}
public String getLink() {
return link;
}
After application download the PDF file to local device, need to update link in your list. Create some database with book information.

Update List View When Clicked on RecycleView Item

I created a listView which is updated on click on item in Reycleview within same page.
Date fetch is working,json data is getting and updated in adpater,but new items is extended with previous data in listview
Layout
First row is RecycleView and Below is Listview, Listview should be update when click on item above in recycleview
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import com.example.sharanjit.fitness.R;
import com.google.gson.JsonArray;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.ArrayList;
public class AllExercise extends AppCompatActivity {
ListView list;
ProgressDialog dialog;
Context context;
GetJSONData getJSONData;
String[] name = {"Abdominals","Arms","Back","Chest","Shoulders","Legs","Cardio"};
private RecyclerView mRecyclerView;
private RecyclerView.Adapter mAdapter;
private RecyclerView.LayoutManager mLayoutManager;
AllExerciseAdapter adapter;
ArrayList<Exercise> arrayList;
boolean first=true;
int pos=0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.allexercises);
dialog=new ProgressDialog(this);
context=getApplicationContext();
getJSONData=new GetJSONData();
arrayList=new ArrayList<>();
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
mRecyclerView = (RecyclerView) findViewById(R.id.recycle);
mRecyclerView.setHasFixedSize(true);
mLayoutManager = new LinearLayoutManager(this,LinearLayoutManager.HORIZONTAL, false);
mRecyclerView.setLayoutManager(mLayoutManager);
mAdapter = new MyAdapter();
mRecyclerView.setAdapter(mAdapter);
new FetchData().execute();
list = (ListView) findViewById(R.id.exercise_list);
list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Intent intent=new Intent(AllExercise.this,ExerciseView.class);
startActivity(intent);
}
});
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id=item.getItemId();
if(id==16908332)
{
finish();
}
return super.onOptionsItemSelected(item);
}
public class MyAdapter extends RecyclerView.Adapter<MyAdapter.ViewHolder> {
public class ViewHolder extends RecyclerView.ViewHolder {
public ImageView imageView;
public ViewHolder(View v) {
super(v);
imageView = (ImageView)v.findViewById(R.id.imageView11);
}
}
public MyAdapter() {
}
#Override
public MyAdapter.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.exercise_item, parent, false);
final ViewHolder vh = new ViewHolder(v);
vh.imageView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
pos=vh.getAdapterPosition();
first=false;
new FetchData().execute();
}
});
return vh;
}
#Override
public void onBindViewHolder(ViewHolder holder, final int position) {
final ViewHolder viewHolder=holder;
viewHolder.imageView.setImageResource(Constants.exercise_images[position]);
}
#Override
public int getItemCount() {
return 7;
}
}
public class AllExerciseAdapter extends ArrayAdapter {
final private Context cx;
final private int pos;
AllExerciseAdapter(Context cx,int pos) {
super(cx, R.layout.allexercise_list_item, arrayList);
this.cx = cx;
this.pos=pos;
}
#Override
public View getView(int position, View vw, ViewGroup group) {
vw = View.inflate(cx, R.layout.allexercise_list_item, null);
ImageView imageView=(ImageView)vw.findViewById(R.id.imageView11);
TextView title=(TextView)vw.findViewById(R.id.textView14);
TextView cat=(TextView)vw.findViewById(R.id.textView13);
title.setText(arrayList.get(position).names);
cat.setText(arrayList.get(position).category);
if(position==0)
Log.e("MS",title.getText().toString());
return vw;
}
}
private class FetchData extends AsyncTask<String,String,String>
{
String url="";
String data="";
#Override
protected void onPreExecute() {
super.onPreExecute();
dialog.setMessage("In Progress...");
dialog.setCancelable(false);
dialog.show();
url="http://www.searchdata.in/fitness/get-exercises.php";
try {
data = URLEncoder.encode("category", "UTF-8") + "=" + URLEncoder.encode(name[pos], "UTF-8");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
}
#Override
protected String doInBackground(String... params) {
String s= getJSONData.getData(url,data);
return s;
}
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
Log.e("sss",s);
try {
JSONArray array=new JSONArray(s);
for(int i=0;i<array.length();i++)
{
JSONObject object=array.getJSONObject(i);
Exercise exercise=new Exercise();
exercise.names=object.getString("name");
exercise.category=object.getString("category");
exercise.decription=object.getString("description");
arrayList.add(exercise);
}
dialog.dismiss();
} catch (JSONException e) {
e.printStackTrace();
}
Log.e("ss",""+first);
adapter = new AllExerciseAdapter(context,pos);
if(!first) {
list.setAdapter(adapter);
adapter.notifyDataSetChanged();
}
else {
list.setAdapter(adapter);
}
}
}
private class Exercise
{
public String names;
public String decription;
public String category;
public String imagePath;
}
}
Just Change your onPostExecute method by below code.
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
Log.e("sss",s);
try {
arrayList=new ArrayList<>();
JSONArray array=new JSONArray(s);
for(int i=0;i<array.length();i++)
{
JSONObject object=array.getJSONObject(i);
Exercise exercise=new Exercise();
exercise.names=object.getString("name");
exercise.category=object.getString("category");
exercise.decription=object.getString("description");
arrayList.add(exercise);
}
dialog.dismiss();
} catch (JSONException e) {
e.printStackTrace();
}
Log.e("ss",""+first);
adapter = new AllExerciseAdapter(context,pos);
list.setAdapter(adapter);
/*if(!first)
{
adapter.notifyDataSetChanged();
}
else {
list.setAdapter(adapter);
}*/
}
You need to make a small change in your code -
if(!first) {
list.setAdapter(adapter);
adapter.notifyDataSetChanged(); // No needed to do for first time
}
else {
list.setAdapter(adapter); // Need to call only once.
adapter.notifyDataSetChanged();// Here you need to call it to reflect changes
}
One more change you need to do in onPostExecute -
try {
JSONArray array=new JSONArray(s);
arraList.clear(); //Add this line
for(int i=0;i<array.length();i++)
Hope it will help :)
This Line Is working for the code:-
adapter = new AllExerciseAdapter(context,arrayList);
adapter.setNotifyOnChange(true); // <-----
list.setAdapter(adapter);

Not getting response from server when using volley for listview?

Am trying to make listview using volley am not getting response from server it throws error JSONException this is my response from server:
[{"UserName":"XXXX ","TaskID":1,"Subject":"fjsdgfgf","DueDate":"2016-01-06T00:00:00","Priority":0,"Owner":762,"OwnerName":null,"RepeatStatus":false,"TaskStatus":"In Progress","RelatedTo":null},{"UserName":"XXX","TaskID":2,"Subject":"test","DueDate":"2016-01-11T00:00:00","Priority":0,"Owner":762,"OwnerName":null,"RepeatStatus":false,"TaskStatus":"Not Started","RelatedTo":null}]
Am not getting response it directly goes to Onerrorresponse it throws of type java.lang.String cannot be converted to JSONArray as a beginner am really confused where am making mistake so far what i have tried is:
This is fragment where i make volley request:
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonArrayRequest;
import com.android.volley.toolbox.Volley;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.List;
/**
* Created by 4264 on 27-01-2016.
*/
public class Task extends Fragment {
private List<Model_Task_List> model_task_lists;
//Creating Views
private RecyclerView recyclerView;
private RecyclerView.LayoutManager layoutManager;
private RecyclerView.Adapter adapter;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_task, container, false);
recyclerView=(RecyclerView)view.findViewById(R.id.my_recycler_view);
LinearLayoutManager layoutManager = new LinearLayoutManager(getContext());
recyclerView.setItemAnimator(new DefaultItemAnimator());
recyclerView.setLayoutManager(layoutManager);
model_task_lists=new ArrayList<Model_Task_List>();
//Showing a progress dialog
String Url="http://XXX.XX.X.XXX/XXX/GetActivitiesByUserID.svc/getlist/GetTask/762";
//Creating a json array request
JsonArrayRequest jsonArrayRequest = new JsonArrayRequest(Url,
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
//Dismissing progress dialog
for(int i = 0; i<response.length(); i++) {
Model_Task_List model_task_list = new Model_Task_List();
try {
JSONObject json = (JSONObject) response
.get(i);
model_task_list.setSubject(json.getString("Subject"));
model_task_list.setUserName(json.getString("UserName"));
model_task_list.setTaskStatus(json.getString("TaskStatus"));
} catch (JSONException e) {
e.printStackTrace();
}
model_task_lists.add(model_task_list);
}
//Finally initializing our adapter
adapter = new Task_List_Adapter(model_task_lists,getContext());
//Adding adapter to recyclerview
recyclerView.setAdapter(adapter);
//calling method to parse json array
// parseData(response);
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(getContext(),error.toString(),Toast.LENGTH_SHORT).show();
Log.e("yog",error.toString());
}
});
//Creating request queue
RequestQueue requestQueue = Volley.newRequestQueue(getContext());
//Adding request to the queue
requestQueue.add(jsonArrayRequest);
return view;
}
}
This is my recyclerview adapter:
import android.content.Context;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import java.util.List;
public class Task_List_Adapter extends RecyclerView.Adapter<Task_List_Adapter.MyViewHolder> {
private List<Model_Task_List> dataSet;
private Context context;
private static data yog;
Model_Task_List modelTaskList=new Model_Task_List();
public void remove(int position)
{
dataSet.remove(position);
notifyItemRemoved(position);
}
public void edit(int position){
dataSet.set(position, modelTaskList);
notifyItemChanged(position);
}
public void setOnItemClickListener(data listener) {
this.yog = listener;
}
public static class MyViewHolder extends RecyclerView.ViewHolder {
// ModelPersonal modelPersonal=new ModelPersonal();
TextView textname;
TextView textaddress;
TextView textphnum;
TextView textdegree;
TextView textemail;
ImageView call;
data datas;
public MyViewHolder(final View itemView) {
super(itemView);
this.textname = (TextView) itemView.findViewById(R.id.subject);
this.textaddress = (TextView) itemView.findViewById(R.id.username);
this.textphnum = (TextView) itemView.findViewById(R.id.status);
itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(yog!=null){
yog.yog(itemView,getLayoutPosition());
}
}
});
// this.imageViewIcon = (ImageView) itemView.findViewById(R.id.imageView);
}
}
public interface data
{
void yog(View v,int position);
}
public Task_List_Adapter(List<Model_Task_List> data,Context context) {
this.dataSet = data;
this.context=context;
}
#Override
public MyViewHolder onCreateViewHolder(ViewGroup parent,
int viewType) {
View view = LayoutInflater.from(parent.getContext())
.inflate(R.layout.task_list_view, parent, false);
MyViewHolder myViewHolder = new MyViewHolder(view);
return myViewHolder;
}
#Override
public void onBindViewHolder(MyViewHolder holder, int position) {
TextView textViewName = holder.textname;
TextView textViewaddress = holder.textaddress;
TextView textViewphnum = holder.textphnum;
TextView textdegree = holder.textdegree;
TextView textemail=holder.textemail;
textViewName.setText("Subject:"+dataSet.get(position).getSubject());
textViewaddress.setText("UserName"+dataSet.get(position).getUserName());
textViewphnum.setText("Status:"+dataSet.get(position).getTaskStatus());
}
#Override
public int getItemCount() {
return dataSet.size();
}
}
This is my model class:
public class Model_Task_List {
public String UserName;
public String Subject;
public String TaskStatus;
public String getSubject() {
return Subject;
}
public void setSubject(String subject) {
Subject = subject;
}
public String getTaskStatus() {
return TaskStatus;
}
public void setTaskStatus(String taskStatus) {
TaskStatus = taskStatus;
}
public String getUserName() {
return UserName;
}
public void setUserName(String userName) {
UserName = userName;
}
public Model_Task_List(String subject, String taskStatus, String userName) {
Subject = subject;
TaskStatus = taskStatus;
UserName = userName;
}
public Model_Task_List(){
}
}
My Jsonresponse:
[{"UserName":"XXXXXX ","TaskID":1,"Subject":"fjsdgfgf","DueDate":"2016-01-06T00:00:00","Priority":0,"Owner":762,"OwnerName":null,"RepeatStatus":false,"TaskStatus":"In Progress","RelatedTo":null},{"UserName":"XXXXX","TaskID":2,"Subject":"test","DueDate":"2016-01-11T00:00:00","Priority":0,"Owner":762,"OwnerName":null,"RepeatStatus":false,"TaskStatus":"Not Started","RelatedTo":null}]
I don't know where am making mistake can anybody helpme!!!
Log cat :
I/Timeline: Timeline: Activity_launch_request time:14940252
02-02 19:22:30.733 11678-11678/XX E/RecyclerView: No adapter attached; skipping layout
02-02 19:22:30.733 11678-11678/XX E/RecyclerView: No adapter attached; skipping layout
02-02 19:22:30.773 11678-11678/XX E/RecyclerView: No adapter attached; skipping layout
02-02 19:22:30.773 11678-11678/XXE/RecyclerView: No adapter attached; skipping layout
02-02 19:22:30.793 11678-11678/xx W/Toast: From XXX, go ahead.
02-02 19:22:30.793 11678-11678/XX E/yog: com.android.volley.ParseError: org.json.JSONException: Value [{"UserName":"XX","TaskID":1,"Subject":"fjsdgfgf","DueDate":"2016-01-06T00:00:00","Priority":0,"Owner":762,"OwnerName":null,"RepeatStatus":false,"TaskStatus":"In Progress","RelatedTo":null},{"UserName":"XXX ","TaskID":2,"Subject":"test","DueDate":"2016-01-11T00:00:00","Priority":0,"Owner":762,"OwnerName":null,"RepeatStatus":false,"TaskStatus":"Not Started","RelatedTo":null}] of type java.lang.String cannot be converted to JSONArray
02-02 19:22:30.893 11678-11678/XXI/Timeline: Timeline: Activity_idle id: android.os.BinderProxy#425c1690 time:14940540
I think the response you are getting from string is String. Please cross verify it at your server end
for more detail please below link
com.android.volley.parse error org.json.jsonexception value of type java.lang.string cannot be converted to jsonArray in Android Volley [SOLVED]

Categories