I have using 3 TAB request,reached and left and using arrayadapter list view, i adding two buttons in list view when i click the button the database value update to refresh value showing in current page, help me..enter image description here
My code is.
public class VisitorListItems {
String visitorname,mobileno,whomtomeet,date,time;
int Reg_id;
Bitmap visitorimg;
public VisitorListItems(String visitorname,String mobileno,String whomtomeet,Bitmap visitorimg,String date,String time,int Reg_id){
this.visitorname=visitorname;
this.mobileno=mobileno;
this.whomtomeet=whomtomeet;
this.visitorimg=visitorimg;
this.date=date;
this.time=time;
this.Reg_id=Reg_id;
}
public String getVisitorname(){
return visitorname;
}
public String getMobileno(){return mobileno; }
public String getWhomtomeet(){
return whomtomeet;
}
public String getDate() { return date; }
public String getTime(){return time;}
public Bitmap getVisitorimg(){
return visitorimg;
}
public int getReg_id(){return Reg_id;}
}
MyListViewAdapter:
public class MyListviewAdapter extends ArrayAdapter<VisitorListItems> {
ArrayList<VisitorListItems> visitorlist=new ArrayList<>();
String RegIdno;
private Button btnallow;
private Button btndeny;
private ProgressDialog pbd;
ConnectionClass connectionClass;
public MyListviewAdapter(Context context,int textViewResourceId, ArrayList<VisitorListItems> objects) {
super(context,textViewResourceId,objects);
visitorlist=objects;
}
#Override
public int getCount() {
return super.getCount();
}
#Override
public View getView(int position, View convertview, ViewGroup parent){
View v=convertview;
LayoutInflater inflater = (LayoutInflater) getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
v = inflater.inflate(R.layout.registrationlisttemplate, null);
connectionClass=new ConnectionClass();
TextView txtvisitorname = (TextView) v.findViewById(R.id.txtvisitorname);
btnallow=(Button)v.findViewById(R.id.btnallow);
btndeny=(Button)v.findViewById(R.id.btndeny);
TextView txtWhomtomeet = (TextView) v.findViewById(R.id.txtWhomtomeet);
TextView txtdate=(TextView)v.findViewById(R.id.txtdate);
TextView txttimein=(TextView)v.findViewById(R.id.txttimein);
final TextView txtregidno=(TextView)v.findViewById(R.id.txtregidno);
TextView txtmobil = (TextView) v.findViewById(R.id.txtmobil);
ImageView imageView = (ImageView) v.findViewById(R.id.imgvisitor);
txtvisitorname.setText(visitorlist.get(position).getVisitorname());
txtWhomtomeet.setText(visitorlist.get(position).getWhomtomeet());
txtmobil.setText(visitorlist.get(position).getMobileno());
imageView.setImageBitmap(visitorlist.get(position).getVisitorimg());
txtdate.setText(visitorlist.get(position).getDate());
txttimein.setText(visitorlist.get(position).getTime());
txtregidno.setText(String.valueOf(visitorlist.get(position).getReg_id()));
txtregidno.setVisibility(View.INVISIBLE);
btnallow.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
RegIdno=txtregidno.getText().toString();
Visitorallow visitorallow=new Visitorallow();
visitorallow.execute("");
}
});
btndeny.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
RegIdno=txtregidno.getText().toString();
Visitordeny visitordeny=new Visitordeny();
visitordeny.execute("");
// Toast.makeText(getContext(),M,Toast.LENGTH_SHORT).show();
}
});
return v;
}
public class Visitorallow extends AsyncTask<String,String,String> {
String Z="";
Boolean isSuccess;
#Override
protected String doInBackground(String... params) {
try{
Connection con=connectionClass.CONN();
if(con==null){
Z="Error in Connection with SQL Server";
}
else {
String query="Update app_Registration set FlatOwner='"+1+"' where Id='"+RegIdno+"'";
PreparedStatement preparedStatement=con.prepareStatement(query);
preparedStatement.executeUpdate();
Z="Update Successfully";
isSuccess=true;
}
}catch (Exception ex){
isSuccess=false;
Z="Exception";
}
return Z;
}
#Override
protected void onPreExecute() {
// super.onPreExecute();
pbd=new ProgressDialog(getContext());
pbd.setMessage("Please Wait...");
pbd.setCancelable(false);
pbd.show();
}
#Override
protected void onPostExecute(String s) {
// super.onPostExecute(s);
if(pbd.isShowing())
pbd.dismiss();
// btndeny.setVisibility(View.GONE);
Toast.makeText(getContext(),s,Toast.LENGTH_SHORT).show();
MyListviewAdapter myAdapter=new MyListviewAdapter(getContext(),R.layout.registrationlisttemplate,visitorlist);
myAdapter.notifyDataSetChanged();
}
}
public class Visitordeny extends AsyncTask<String,String,String> {
String Z="";
Boolean isSuccess;
#Override
protected String doInBackground(String... params) {
try{
Connection con=connectionClass.CONN();
if(con==null){
Z="Error in Connection with SQL Server";
}
else {
String query="Update app_Registration set FlatOwner='"+0+"' where Id='"+RegIdno+"'";
PreparedStatement preparedStatement=con.prepareStatement(query);
preparedStatement.executeUpdate();
Z="Update Successfully";
isSuccess=true;
}
}catch (Exception ex){
isSuccess=false;
Z="Exception";
}
return Z;
}
#Override
protected void onPreExecute() {
// super.onPreExecute();
pbd=new ProgressDialog(getContext());
pbd.setMessage("Please Wait...");
pbd.setCancelable(false);
pbd.show();
}
#Override
protected void onPostExecute(String s) {
// super.onPostExecute(s);
if(pbd.isShowing())
pbd.dismiss();
// btndeny.setVisibility(View.GONE);
Toast.makeText(getContext(),s,Toast.LENGTH_SHORT).show();
}
}
}
VisitorList code:
public class VisitorList extends Fragment {
// private ProgressDialog pbbar;
//private ProgressBar pbbar;
private ProgressDialog pbd;
private ListView lstview;
ConnectionClass connectionClass;
String Y = "";
String mobileno;
int RegIdNo;
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
mobileno=getActivity().getIntent().getStringExtra("user_name");
View rootView = inflater.inflate(R.layout.visitorlistslide, container, false);
lstview = (ListView) rootView.findViewById(R.id.lstview);
// txtregid=(TextView)rootView.findViewById(R.id.txtregid);
connectionClass = new ConnectionClass();
Fetch fetch = new Fetch();
fetch.execute("");
return rootView;
}
public class Fetch extends AsyncTask<String, String, String> {
String z = "";
ArrayList<VisitorListItems> visitorList=new ArrayList<>();
#Override
protected void onPreExecute() {
pbd=new ProgressDialog(getActivity());
pbd.setMessage("Please Wait...");
pbd.setCancelable(false);
pbd.show();
}
#Override
protected void onPostExecute(String r) {
// pbbar.setVisibility(View.GONE);
if (pbd.isShowing())
pbd.dismiss();
// txtregid.setText(String.valueOf(Reg_Id));
Toast.makeText(getActivity(), r, Toast.LENGTH_SHORT).show();
MyListviewAdapter myAdapter=new MyListviewAdapter(getActivity(),R.layout.registrationlisttemplate,visitorList);
myAdapter.notifyDataSetChanged();
lstview.setAdapter(myAdapter);
}
#Override
protected String doInBackground(String... params) {
try {
Connection con = connectionClass.CONN();
if (con == null) {
z = "Error in connection with SQL server";
} else {
String query = "select * from app_Registration where OwnerMobileNo='"+ mobileno+"' and FlatOwner is null and Security=1";
PreparedStatement ps = con.prepareStatement(query);
ResultSet rs = ps.executeQuery();
ArrayList data1 = new ArrayList();
while (rs.next()) {
//Reg_Id=rs.getInt("Id");
RegIdNo=rs.getInt("Id");
String r=rs.getString("VisitorImg");
//Convertong Images string to bitmap
byte[] decodeString = Base64.decode(r, Base64.DEFAULT);
Bitmap decodebitmap = BitmapFactory.decodeByteArray(decodeString,0, decodeString.length);
visitorList.add(new VisitorListItems("VisitorName : " + rs.getString("VisitorName"),"Whomtomeet : " + rs.getString("Whomtomeet"),"Mobile No. : " + rs.getString("MobileNo"),decodebitmap,"Visit Date :"+rs.getString("datein"),rs.getString("timein"),RegIdNo));
}
z = "Visitor Success";
}
} catch (Exception ex) {
z = "Error retrieving data from table";
}
return z;
}
}
}
Fetch data from database in onResume() method of Fragment. Then it will be the refreshed data.
Related
I have create two Fragments with two TAB one for Register another one for Showing data,i am using custom Array-adapter,When i click the save button in fragment one,the database updated data will showing to second fragment listview and i have create two buttons in listview 1 for allow 2 for deny i click allow button the data will updated to "true" in backend database as well as data list hide how to do.. i have using database MS SQLServer. some one Help Me Please..
My Code is
public class MyListviewAdapter extends ArrayAdapter<VisitorListItems> {
ArrayList<VisitorListItems> visitorlist=new ArrayList<>();
String RegIdno;
private Button btnallow;
private Button btndeny;
private ProgressDialog pbd;
ConnectionClass connectionClass;
public MyListviewAdapter(Context context,int textViewResourceId, ArrayList<VisitorListItems> objects) {
super(context,textViewResourceId,objects);
visitorlist=objects;
}
#Override
public int getCount() {
return super.getCount();
}
#Override
public View getView(int position, View convertview, ViewGroup parent){
View v=convertview;
LayoutInflater inflater = (LayoutInflater) getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
v = inflater.inflate(R.layout.registrationlisttemplate, null);
connectionClass=new ConnectionClass();
TextView txtvisitorname = (TextView) v.findViewById(R.id.txtvisitorname);
btnallow=(Button)v.findViewById(R.id.btnallow);
btndeny=(Button)v.findViewById(R.id.btndeny);
TextView txtWhomtomeet = (TextView) v.findViewById(R.id.txtWhomtomeet);
TextView txtdate=(TextView)v.findViewById(R.id.txtdate);
TextView txttimein=(TextView)v.findViewById(R.id.txttimein);
final TextView txtregidno=(TextView)v.findViewById(R.id.txtregidno);
TextView txtmobil = (TextView) v.findViewById(R.id.txtmobil);
ImageView imageView = (ImageView) v.findViewById(R.id.imgvisitor);
txtvisitorname.setText(visitorlist.get(position).getVisitorname());
txtWhomtomeet.setText(visitorlist.get(position).getWhomtomeet());
txtmobil.setText(visitorlist.get(position).getMobileno());
imageView.setImageBitmap(visitorlist.get(position).getVisitorimg());
txtdate.setText(visitorlist.get(position).getDate());
txttimein.setText(visitorlist.get(position).getTime());
txtregidno.setText(String.valueOf(visitorlist.get(position).getReg_id()));
txtregidno.setVisibility(View.INVISIBLE);
btnallow.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
RegIdno=txtregidno.getText().toString();
Visitorallow visitorallow=new Visitorallow();
visitorallow.execute("");
// Toast.makeText(getContext(),M,Toast.LENGTH_SHORT).show();
// Log.d("Test","hello");
//System.out.println("allow button");
//String r=v.getTex
}
});
btndeny.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
RegIdno=txtregidno.getText().toString();
Visitordeny visitordeny=new Visitordeny();
visitordeny.execute("");
// Toast.makeText(getContext(),M,Toast.LENGTH_SHORT).show();
}
});
return v;
}
public class Visitorallow extends AsyncTask<String,String,String> {
String Z="";
Boolean isSuccess;
#Override
protected String doInBackground(String... params) {
try{
Connection con=connectionClass.CONN();
if(con==null){
Z="Error in Connection with SQL Server";
}
else {
String query="Update app_Registration set FlatOwner='"+1+"' where Id='"+RegIdno+"'";
PreparedStatement preparedStatement=con.prepareStatement(query);
preparedStatement.executeUpdate();
Z="Update Successfully";
isSuccess=true;
}
}catch (Exception ex){
isSuccess=false;
Z="Exception";
}
}catch (Exception ex){
isSuccess=false;
return Z="Exception";Z;
}
return Z;
#Override
protected void onPreExecute() {
// super.onPreExecute();
pbd=new ProgressDialog(getContext());
pbd.setMessage("Please Wait...");
pbd.setCancelable(false);
pbd.show();
}
#Override
protected void onPostExecute(String s) {
// super.onPostExecute(s);
if(pbd.isShowing())
pbd.dismiss();
// btndeny.setVisibility(View.GONE);
Toast.makeText(getContext(),s,Toast.LENGTH_SHORT).show();
}
}
Display value Code is Below:
public class VisitorList extends Fragment {
private ProgressDialog pbd;
private ListView lstview;
private TextView txttimein,txtdate,txtregid;
ConnectionClass connectionClass;
String Y = "";
String mobileno;
int RegIdNo;
#Overridepublic View onCreateView(LayoutInflater inflater, ViewGroup container,
protected void onPreExecute( Bundle savedInstanceState) {
//mobileno=getActivity().getIntent().getStringExtra("user_name");
View rootView = inflater.onPreExecuteinflate(R.layout.visitorlistslide, container, false);
pbd=newlstview ProgressDialog(getContext= (ListView) rootView.findViewById(R.id.lstview);
pbdtxttimein=(TextView)rootView.setMessagefindViewById("PleaseR.id.txttimein);
txtdate=(TextView)rootView.findViewById(R.id."txtdate);
pbd.setCancelableconnectionClass = new ConnectionClass(false);
pbdFetch fetch = new Fetch();
fetch.showexecute("");
return rootView;
}
public class Fetch extends AsyncTask<String, String, String> {
String z = "";
ArrayList<VisitorListItems> visitorList=new ArrayList<>();
#Override
protected void onPostExecuteonPreExecute(String s) {
// super pbd=new ProgressDialog(getActivity());
pbd.onPostExecutesetMessage(s"Please Wait...");
pbd.setCancelable(false);
pbd.show();
}
#Override
protected void onPostExecute(String r) {
if (pbd.isShowing())
pbd.dismiss();
Toast.makeText(getActivity(), r, Toast.LENGTH_SHORT).show();
MyListviewAdapter myAdapter=new MyListviewAdapter(getActivity(),R.layout.registrationlisttemplate,visitorList);
lstview.setAdapter(myAdapter);
}
#Override
protected String doInBackground(String... params) {
try {
Connection con = connectionClass.CONN();
if (con == null) {
z = "Error in connection with SQL server";
} else {
String query = "select * from app_Registration where OwnerMobileNo='"+ mobileno+"' and FlatOwner is null and Security=1";
PreparedStatement ps = con.prepareStatement(query);
ResultSet rs = ps.executeQuery();
ArrayList data1 = new ArrayList();
while (rs.next()) {
//Reg_Id=rs.getInt("Id");
RegIdNo=rs.setVisibilitygetInt(View"Id");
String r=rs.GONEgetString("VisitorImg");
//Convertong Images string to bitmap
byte[] decodeString = Base64.makeTextdecode(getContextr, Base64.DEFAULT);
Bitmap decodebitmap = BitmapFactory.decodeByteArray(decodeString,0, decodeString.length);
visitorList.add(new VisitorListItems("VisitorName : " + rs.getString("VisitorName"),s"Whomtomeet : " + rs.getString("Whomtomeet"),Toast"Mobile No.LENGTH_SHORT : " + rs.getString("MobileNo"),decodebitmap,"Visit Date :"+rs.showgetString("datein"),rs.getString("timein"),RegIdNo));
}
z = "Success";
}
} catch (Exception ex) {
z = "Error retrieving data from table";
}
return z;
}
}
}
This is the tiny code to refresh fragments:
public void refresh(){
FragmentTransaction ft = getFragmentManager().beginTransaction();
ft.detach(this).attach(this).commit();
}
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;
}
}
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.
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
I put a limit of 15 records to be displayed in my listview. The 15 records successfully displayed but when i clicked on load more button, it add the previous 15 records and the new records too. Here is my async task where more records is being added. I use articlesAdapter.notifyDataSetChanged(); set too but the issue remains. i believe it has something to do with articlesFiltered.size()/15)+1.
public class ActusScreen extends BaseActivity implements OnClickListener {
private DisplayImageOptions options;
ImageLoader imageLoader;
String link;
//...
final int NONE=0;
final int THEME=1;
final int SEARCH=2;
final int THEME_TO_SEARCH=3;
final int SEARCH_RESULTS=4;
final int THEME_TO_SEARCH_RESULTS=5;
int MODE=NONE;
public ArrayList<Article> articles;
public ArrayList<Article> articlesFiltered;
public ArrayList<Theme> themes;
public ArrayList<Theme> themeFiltered;
public static int titleIndex=0;
static boolean original_view = false;
RelativeLayout adLayout;
ListView themesList;
RelativeLayout searchLayout;
EditText searchField;
Button back, theme;
StringBuilder builder;
ScrollView scrollme;
ThemesAdapter themeAdapter;
ArticlesAdapter articlesAdapter;
TextView header_text;
ActusScreen context;
ProgressDialog pd;
ImageView image_actus;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.actus);
context=this;
back=(Button)findViewById(R.id.envoye);
back.setOnClickListener(this);
back.setVisibility(View.GONE);
theme=(Button)findViewById(R.id.theme);
theme.setOnClickListener(this);
Button search=(Button)findViewById(R.id.search);
search.setOnClickListener(this);
header_text = (TextView)findViewById(R.id.text_titre);
header_text.setText(getResources().getText(R.string.actus).toString());
adLayout=(RelativeLayout)findViewById(R.id.adLayout);
themeAdapter=new ThemesAdapter(this);
themesList=(ListView)findViewById(R.id.themesList);
themesList.setAdapter(themeAdapter);
themesList.setVisibility(View.GONE);
SelectedArticle.mtypo=1;
articlesAdapter=new ArticlesAdapter(this);
ListView articlesList=(ListView)findViewById(R.id.articlesList);
articlesList.setAdapter(articlesAdapter);
searchLayout=(RelativeLayout)findViewById(R.id.searchLayout);
searchLayout.setVisibility(View.GONE);
searchField=(EditText)findViewById(R.id.keyword);
Button valid=(Button)findViewById(R.id.valid);
valid.setOnClickListener(this);
new GetAllArticlesTask().execute();
image_actus = (ImageView)findViewById(R.id.image);
image_actus.setOnClickListener(new OnClickListener(){
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
String url = link;
Intent i = new Intent(Intent.ACTION_VIEW);
i.setData(Uri.parse(url));
startActivity(i);
}
});
options = new DisplayImageOptions.Builder()
// .showStubImage(R.drawable.ic_launcher)
.displayer(new RoundedBitmapDisplayer(3))
.cacheInMemory()
.cacheOnDisc()
.build();
imageLoader = ImageLoader.getInstance();
imageLoader.init(ImageLoaderConfiguration.createDefault(getApplicationContext()));
new backTask().execute("");
}
#Override
protected void onStart() {
// TODO Auto-generated method stub
//FavoriteScreen.flagx=1;
super.onStart();
}
#Override
public void onClick(View v) {
switch(v.getId()){
case R.id.envoye:
back();
break;
case R.id.theme:
if(themesList.getVisibility()==View.VISIBLE)
themesList.setVisibility(View.GONE);
else
themesList.setVisibility(View.VISIBLE);
break;
case R.id.search:
search();
break;
case R.id.valid:
searchLayout.setVisibility(View.GONE);
if(MODE==SEARCH)
MODE=SEARCH_RESULTS;
else
MODE=THEME_TO_SEARCH_RESULTS;
filterArticles();
break;
}
}
public void search(){
switch(MODE){
case SEARCH_RESULTS:
searchLayout.setVisibility(View.VISIBLE);
MODE=SEARCH;
break;
case THEME_TO_SEARCH_RESULTS:
searchLayout.setVisibility(View.VISIBLE);
MODE=THEME_TO_SEARCH;
break;
case THEME:
searchLayout.setVisibility(View.VISIBLE);
MODE=THEME_TO_SEARCH;
break;
case NONE:
searchLayout.setVisibility(View.VISIBLE);
back.setVisibility(View.VISIBLE);
theme.setVisibility(View.GONE);
MODE=SEARCH;
break;
}
}
public void back(){
switch(MODE){
case SEARCH_RESULTS:
searchLayout.setVisibility(View.VISIBLE);
MODE=SEARCH;
break;
case THEME_TO_SEARCH_RESULTS:
searchLayout.setVisibility(View.VISIBLE);
MODE=THEME_TO_SEARCH;
break;
case THEME:
back.setVisibility(View.GONE);
theme.setVisibility(View.VISIBLE);
/*
*
Intent intent = getIntent();
finish();
startActivity(intent);
*/
articlesAdapter=new ArticlesAdapter(this);
ListView articlesList=(ListView)findViewById(R.id.articlesList);
articlesList.setAdapter(articlesAdapter);
//ActusScreen.titleIndex=0;
ArticlesAdapter.mode = true;
titleIndex=0;
new GetAllArticlesTask().execute();
header_text.setText(getResources().getText(R.string.actus).toString());
MODE=NONE;
break;
case SEARCH:
searchLayout.setVisibility(View.GONE);
back.setVisibility(View.GONE);
theme.setVisibility(View.VISIBLE);
MODE=NONE;
copyArticles();
articlesAdapter.notifyDataSetChanged();
break;
case THEME_TO_SEARCH:
searchLayout.setVisibility(View.GONE);
MODE=THEME;
copyArticles();
articlesAdapter.notifyDataSetChanged();
break;
}
}
private void copyArticles() {
if(articles!=null){
if(articlesFiltered==null)
articlesFiltered=new ArrayList<Article>();
else
articlesFiltered.clear();
for(Article a: articles)
articlesFiltered.add(a);
}
}
public void filterArticles(){
String key=searchField.getText().toString().toLowerCase();
if(key.length()>0){
if(articlesFiltered!=null){
articlesFiltered.clear();
System.gc();
}
for(Article a: articles){
if(a.name.toLowerCase().contains(key))
articlesFiltered.add(a);
}
articlesAdapter.notifyDataSetChanged();
}
}
private class GetAllArticlesTask extends AsyncTask<Void, Void, Void> {
#Override
public Void doInBackground(Void... params) {
if(Globals.themes==null)
Globals.themes=HTTPFunctions.getThemesList();
if(articles!=null){
articles.clear();
System.gc();
}
articles=HTTPFunctions.getAllArticles();
copyArticles();
return null;
}
#Override
public void onPreExecute() {
pd = ProgressDialog.show(context, "", context.getResources().getString(R.string.loading), true, false);
}
#Override
public void onPostExecute(Void result) {
pd.dismiss();
articlesAdapter.notifyDataSetChanged();
themeAdapter.notifyDataSetChanged();
}
}
private class GetThemeArticlesTask extends AsyncTask<String, Void, Void> {
#Override
public Void doInBackground(String... params) {
if(articles!=null){
articles.clear();
System.gc();
}
articles=HTTPFunctions.getThemeArticles(params[0]);
//begin 06/03; articles.theme_id not set by HTTPFunctions when a specific theme is selected; need to set it explicitly
for (Article a : articles)
a.theme_id=params[0];
//end
System.out.println("theme article: "+ HTTPFunctions.getThemeArticles(params[0]));
copyArticles();
return null;
}
#Override
public void onPreExecute() {
pd = ProgressDialog.show(context, "", context.getResources().getString(R.string.loading), true, false);
}
#Override
public void onPostExecute(Void result) {
pd.dismiss();
articlesAdapter.notifyDataSetChanged();
}
}
private class GetMoreArticlesTask extends AsyncTask<Void, Void, Void> {
#Override
public Void doInBackground(Void... params) {
ArrayList<Article>moreArticles=HTTPFunctions.getMoreArticles(addOne((articlesFiltered.size()/15)));
if(moreArticles!=null){
articles.addAll(articles);
copyArticles();
}
return null;
}
#Override
public void onPreExecute() {
pd = ProgressDialog.show(context, "", context.getResources().getString(R.string.loading), true, false);
}
#Override
public void onPostExecute(Void result) {
pd.dismiss();
articlesAdapter.notifyDataSetChanged();
}
}
public void articleSelected(int id){
Globals.copyArticles(articlesFiltered);
Intent i=new Intent(context, SelectedArticle.class);
i.putExtra("id", id);
//begin
//i.putExtra("title", ArticlesAdapter.selected);
if (titleIndex==0){
String title=Util.getTitleName(articlesFiltered.get(id).type, articlesFiltered.get(id).theme_id);
i.putExtra("title", title);
}
else{
String title=ArticlesAdapter.selected.toUpperCase();
i.putExtra("title", title);
}
//end
context.startActivity(i);
}
public void themeSelected(int id){
themesList.setVisibility(View.GONE);
MODE=THEME;
theme.setVisibility(View.GONE);
back.setVisibility(View.VISIBLE);
ArticlesAdapter.mode = false;
//begin 06/03
//ArticlesAdapter.selected=Globals.themes.get(id).name;
//header_text.setText(Globals.themes.get(id).name.toUpperCase());
Spanned name=Html.fromHtml(Globals.themes.get(id).name);
System.out.println("spanned name: "+ name);
ArticlesAdapter.selected=name.toString().toUpperCase();
header_text.setText(name.toString().toUpperCase());
//end
System.out.println("theme_name: "+ Globals.themes.get(id).name);
new GetThemeArticlesTask().execute(Globals.themes.get(id).id);
}
public void loadMore(){
new GetMoreArticlesTask().execute();
}
#Override
protected void onResume() {
// TODO Auto-generated method stub
if (original_view==true){
new GetAllArticlesTask().execute();
theme.setVisibility(View.VISIBLE);
back.setVisibility(View.GONE);
header_text.setText(getResources().getText(R.string.actus).toString());
original_view=false;
}
super.onResume();
}
#Override
protected void onPause() {
// TODO Auto-generated method stub
SelectedReglementation.setview=true;
super.onPause();
}
class backTask extends AsyncTask<String, Void, ArrayList<Post>> {
#Override
protected void onPreExecute() {
// TODO Auto-generated method stub
super.onPreExecute();
}
#Override
protected ArrayList<Post> doInBackground(String... urls) {
ArrayList<Post> newpostarraylist=new ArrayList<Post>();
try{
URL url = new URL("");
BufferedReader reader = null;
builder = new StringBuilder();
try {
reader = new BufferedReader(new InputStreamReader(url.openStream(), "UTF-8"));
for (String line; (line = reader.readLine()) != null;) {
builder.append(line.trim());
}
} finally {
if (reader != null) try { reader.close(); } catch (IOException logOrIgnore) {}
}
System.out.println("Builder: "+ builder);
}catch(Exception ex){}
return newpostarraylist;
}
#Override
protected void onPostExecute(ArrayList<Post> result) {
String[] banner_image = builder.toString().split(";");
imageLoader.displayImage(banner_image[2], image_actus,options);
link = banner_image[1];
}
}
public int addOne(int i){
return i+1;
}
}
and My article adapter
public class ArticlesAdapter extends BaseAdapter {
ActusScreen main;
ImageLoader imageLoader;
String imageUrl="";
public static String selected="";
public static boolean mode=false;
int x=0;
//disable a.theme_id null pointer wh
public static int bine=0;
public ArticlesAdapter(ActusScreen m) {
main=m;
imageLoader=new ImageLoader(m);
}
public int getCount() {
if(main.articlesFiltered!=null)
return main.articlesFiltered.size();
return 0;
}
public Object getItem(int position) {
return null;
}
public long getItemId(int position) {
return 0;
}
public View getView(final int position, View convertView, ViewGroup parent) {
final ViewHolder holder;
if (convertView==null) {
convertView=newView(position, parent);
holder = new ViewHolder();
holder.image=(ImageView)convertView.findViewById(R.id.image);
holder.remove=(ImageView)convertView.findViewById(R.id.remove);
holder.title=(TextView)convertView.findViewById(R.id.title);
holder.text_title=(TextView)convertView.findViewById(R.id.text_title);
holder.more=(RelativeLayout)convertView.findViewById(R.id.moreLayout);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
Article a=main.articlesFiltered.get(position);
imageLoader.DisplayImage(String.format(imageUrl, a.image), holder.image);
String str = a.name;
int length = str.length();
String newStr = a.name;
if (length>65)
newStr = str.replaceAll("^(.{74})(.*)$","$1...");
holder.title.setText(Html.fromHtml(newStr));
holder.text_title.setText(selected.toUpperCase());
holder.remove.setVisibility(View.GONE);
if (holder.text_title.equals(null))
holder.text_title.setText("t");
if(position==main.articlesFiltered.size()-1 && main.articlesFiltered.size()<=45 && main.articlesFiltered.size()%15==0)
holder.more.setVisibility(View.VISIBLE);
else
holder.more.setVisibility(View.GONE);
convertView.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
main.articleSelected(position);
SelectedArticle.mtypo=1;
}
});
holder.more.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
main.loadMore();
}
});
if (ActusScreen.titleIndex==0){
...
}
}
return(convertView);
}
private View newView(int position, ViewGroup parent) {
return(main.getLayoutInflater().inflate(R.layout.articles_row, parent, false));
}
class ViewHolder {
ImageView image, remove;
TextView title;
TextView text_title;
RelativeLayout more;
}
}
UPDATE
and the HttpFunction getMoreArticles()
public static ArrayList<Article> getMoreArticles(int page){
String url=LAST_ARTICLE_URL;
if(url.endsWith(".php"))
url+="?page="+page;
else
url+="&page="+page;
String response=getResponse(url);
if(!ERROR.equals(response)){
return JsonParsingFunctions.parseArticles(response);
}
return null;
}
What is happening is concatenation in the method call. articlesFiltered.size()/15 is giving 1, then the +1 is not ADDING 1, it is concatenating 1, i.e 1+1 = 11 NOT 2. You could create a method
public int addOne(int i){
return i+1;
}
and use
ArrayList<Article>moreArticles=HTTPFunctions.getMoreArticles(addOne((articlesFiltered.size()/15)));
That should work providing the rest of the code is good
what variable is your adapter?
you notify your adapter but i don't see that you add datas to your articlesAdapter