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.
Related
Please find me to solve this issue , i have a list of image url in a json api ,list url api is calling from background task and after compliting called notify method its not showing
but the Recyclerview doesn't refresh - only if I go back and reopen the activity - the new data is shown.
So how can I notify the adapter that there's new data to display?
1.WallpaperFragmentAdapter.java
public class WallpaperFragmentAdapter extends Fragment {
List<WallpaperMain> wallpaperList = new ArrayList<WallpaperMain>();
WallPaperAdapter wallPaperAdapter;
#Bind(R.id.recyclerView)
RecyclerView recyclerView;
private int tabId ;
public void settabId(int tabId){
this.tabId=tabId;
}
public static Fragment newInstance(Context context) {
WallpaperFragmentAdapter f = new WallpaperFragmentAdapter();
return f;
}
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
ViewGroup root = (ViewGroup) inflater.inflate(R.layout.content_main, null);
setUpView(root);
return root;
}
void setUpView(ViewGroup root){
ButterKnife.bind(this, root);
setUPList();
}
void setUPList(){
new WallPaperListDownlaoderTask().execute("http://localhost:8080/api/motivation/wallpaper/wallpaper");
recyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
GridLayoutManager gridLayoutManager = new GridLayoutManager(getActivity(),3);
wallPaperAdapter = new WallPaperAdapter(wallpaperList,getActivity());
recyclerView.setAdapter(wallPaperAdapter);
recyclerView.setLayoutManager(gridLayoutManager);
System.out.println(wallPaperAdapter);
recyclerView.addOnItemTouchListener(new RecyclerTouchListener(getActivity(), recyclerView, new RecyclerTouchListener.ClickListener() {
#Override
public void onClick(View view, int position) {
Intent intent;
intent = new Intent(getActivity(), WallpaperDeatilsActivity.class);
startActivity(intent);
}
#Override
public void onLongClick(View view, int position) {
}
}));
}
class WallPaperListDownlaoderTask extends AsyncTask<String,Integer,JSONArray> {
OkHttpClient client = new OkHttpClient();
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected JSONArray doInBackground(String... params) {
String url =params[0];
Request request = new Request.Builder()
.url(url)
.build();
try{
Response response = client.newCall(request).execute();
String apiResponseString=response.body().string();
System.out.println("response.body().toString() ---- "+apiResponseString );
JSONArray jsonArray = new JSONArray(apiResponseString);
List<WallpaperMain> wallpaperMains = new ArrayList<>();
for(int index =0;index<jsonArray.length();index++){
try {
JSONObject wallpaperMainsJsonObj = jsonArray.getJSONObject(index);
WallpaperMain wallpaperMain = new WallpaperMain();
wallpaperMain.setId(wallpaperMainsJsonObj.getInt("id"));
Wallpaper wallpaper = new Wallpaper();
JSONObject wallpaperJsonObj = wallpaperMainsJsonObj.getJSONObject("wallpaper");
wallpaper.setLarge(wallpaperJsonObj.getString("large"));
wallpaperMain.setWallpaper(wallpaper);
wallpaperMains.add(wallpaperMain);
} catch (JSONException e) {
e.printStackTrace();
}
}
wallpaperList =wallpaperMains;
return null;
}catch (IOException e){
Log.v("",e.toString());
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(JSONArray jsonArray) {
super.onPostExecute(jsonArray);
System.out.println(wallPaperAdapter);
wallPaperAdapter.notifyDataSetChanged();
recyclerView.setAdapter(wallPaperAdapter);
System.out.println(wallpaperList.size());
}
}
}
2.WallPaperAdapter.java
public class WallPaperAdapter extends RecyclerView.Adapter<WallPaperAdapter.MyViewHolder>{
private List<WallpaperMain> wallpaperMains;
private Context context;
public WallPaperAdapter(List<WallpaperMain> wallpaperMains,Context context){
this.wallpaperMains =wallpaperMains;
this.context=context;
}
#Override
public WallPaperAdapter.MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View itemLayoutView = LayoutInflater.from(parent.getContext()).inflate(R.layout.wallpaper_item, null);
WallPaperAdapter.MyViewHolder viewHolder = new WallPaperAdapter.MyViewHolder(itemLayoutView);
return viewHolder;
}
#Override
public void onBindViewHolder(MyViewHolder holder, int position) {
Glide.with(context)
.load("http://localhost:8080/api/motivation/wallpaper/large/37l")
.into(holder.waIlpapermageView);
// holder.waIlpapermageView.setImageResource(R.drawable.name);
}
#Override
public int getItemCount() {
return wallpaperMains.size();
}
public class MyViewHolder extends RecyclerView.ViewHolder {
ImageView waIlpapermageView;
public MyViewHolder(View itemView) {
super(itemView);
waIlpapermageView =(ImageView) itemView.findViewById(R.id.wallpaperItem_imageView);
}
}
}
OUTPUT I am getting bellow
In your doInBackground method , instead of
wallpaperList = wallpaperMains;
use
wallpaperList.clear();
wallpaperList.addAll(wallpaperMains);
In onPostExecute()
#Override
protected void onPostExecute(JSONArray jsonArray) {
super.onPostExecute(jsonArray);
System.out.println(wallPaperAdapter);
wallPaperAdapter.notifyDataSetChanged();
System.out.println(wallpaperList.size());
}
Try this...
Please clear your Arraylist before adding the values wallpaperList.clear(); On onPreExecute() method.
recyclerView.setAdapter(wallPaperAdapter);
wallPaperAdapter.notifyDataSetChanged();
Whenever your ArrayList value is changing usenotifyDataSetChanged(); it will refresh your Recylierview
I had an ListVew where I have to show the orders List from Database.I have Multiple orders in Mysql Database but only one order is continuously repeating in ListVew.Any help regarding this is Appreciated.
Here is my Adapter Class
public class OrderApprovalAdapter extends ArrayAdapter
{
List list1 = new ArrayList();
Context context;
public OrderApprovalAdapter(#NonNull Context context, #NonNull int Resource)
{
super(context, Resource);
this.context = context;
}
#Override
public void add(#Nullable Object object)
{
super.add(object);
list1.add(object);
}
#Override
public int getCount()
{
return list1.size();
}
#Override
public Object getItem(int position)
{
return list1.get(position);
}
#Override
public long getItemId(int position)
{
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent)
{
final OrderApprovalAdapter.ContactHolder contactHolder;
View row;
row = convertView;
if (row == null)
{
LayoutInflater layoutInflater = (LayoutInflater) this.getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
row = layoutInflater.inflate(R.layout.order_approval_format, parent, false);
contactHolder = new ContactHolder();
contactHolder.date = (TextView) row.findViewById(R.id.invoice_date);
contactHolder.orderid = (TextView) row.findViewById(R.id.invoice_no);
contactHolder.shopname = (TextView) row.findViewById(R.id.shop_name);
contactHolder.ownername = (TextView) row.findViewById(R.id.owner_name);
contactHolder.mobile=(TextView) row.findViewById(R.id.mobile_noo);
contactHolder.location=(TextView)row.findViewById(R.id.location);
contactHolder.itemscount=(TextView)row.findViewById(R.id.items);
contactHolder.amount=(TextView)row.findViewById(R.id.total);
contactHolder.Approval=(Button)row.findViewById(R.id.Approve_btn);
contactHolder.Decline=(Button)row.findViewById(R.id.decline_btn);
row.setTag(contactHolder);
} else
{
contactHolder = (ContactHolder) row.getTag();
}
final OrderApprovalDetails contacts = (OrderApprovalDetails) this.getItem(position);
contactHolder.date.setText(contacts.getDate());
contactHolder.orderid.setText(contacts.getOrderid());
contactHolder.shopname.setText(contacts.getShopname());
contactHolder.ownername.setText(contacts.getOwnername());
contactHolder.mobile.setText(contacts.getMobile());
contactHolder.location.setText(contacts.getLocation());
contactHolder.itemscount.setText(contacts.getItemscount());
contactHolder.amount.setText(contacts.getAmount());
contactHolder.Approval.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
Toast.makeText(context, "Approved", Toast.LENGTH_SHORT).show();
}
});
contactHolder.Decline.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
Toast.makeText(context, "Decline", Toast.LENGTH_SHORT).show();
}
});
return row;
}
static class ContactHolder
{
TextView date,orderid,shopname,ownername,mobile,location,itemscount,amount;
Button Approval,Decline;
}
}
Retriving Data From Database
class OrdersListBackgroundTask extends AsyncTask<Void,Void,String>
{
#Override
protected void onPreExecute()
{
OrdersList_url="http://10.0.2.2/accounts/OrderForm2.php";
}
#Override
protected String doInBackground(Void... params)
{
try {
URL url=new URL(OrdersList_url);
HttpURLConnection httpURLConnection=
(HttpURLConnection)url.openConnection();
InputStream is= httpURLConnection.getInputStream();
InputStreamReader isr=new InputStreamReader(is);
BufferedReader br=new BufferedReader(isr);
StringBuilder sb=new StringBuilder();
while ((JSON_STRING4=br.readLine())!=null)
{
sb.append(JSON_STRING4+ "");
}
br.close();
is.close();
httpURLConnection.disconnect();
return sb.toString().trim();
} catch (MalformedURLException e)
{
e.printStackTrace();
} catch (IOException e)
{
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(String result)
{
//TextView tv=(TextView)findViewById(R.id.tv);
//tv.setText(result);
json_string4=result;
}
}
Sending Through intent to Next Page
public void Orders_List(View v)//Button click
{
if (json_string4==null)
{
Toast.makeText(this, "Get Orders First", Toast.LENGTH_SHORT).show();
}else
{
Intent i1=new Intent(this,OrdersList.class);
i1.putExtra("json_data4",json_string4);
startActivity(i1);
}
}
Usage in MainActivity
json_string4=getIntent().getExtras().getString("json_data4");
listView_Orders=(ListView)findViewById(R.id.listViewOrderlist);
listView_Orders.setItemsCanFocus(true);
search_filter=(EditText)findViewById(R.id.search_et);
orderApprovalAdapter=new
OrderApprovalAdapter(this,R.layout.order_approval_format);
listView_Orders.setAdapter(orderApprovalAdapter);
//listView_Orders.setTextFilterEnabled(true);
try
{
jsonObject=new JSONObject(json_string4);
jsonArray=jsonObject.getJSONArray("orders");
int count=0;
for (int i=0;i<jsonArray.length();i++)
{
JSONObject jo=jsonArray.getJSONObject(i);
date=jo.getString("date");
orderid=jo.getString("orderid");
shopname=jo.getString("shopname");
ownername=jo.getString("ownername");
mobile=jo.getString("mobile");
location=jo.getString("location");
items=jo.getString("items_count");
amount=jo.getString("amount");
OrderApprovalDetails orderApprovalDetails=new OrderApprovalDetails(date,orderid,shopname,ownername,mobile,location,items,amount,Approve,Decline);
orderApprovalAdapter.add(orderApprovalDetails);
}
} catch (JSONException e)
{
e.printStackTrace();
}
}
OrderApprovalDetails Class
public class OrderApprovalDetails
{
public static String
date,orderid,shopname,ownername,mobile,location,itemscount,amount;
public static Button Approval,Decline;
public OrderApprovalDetails(String date,String orderid,String shopname,String ownername,String mobile,String location,String itemscount,String amount,Button Approval,Button Decline)
{
this.setDate(date);
this.setOrderid(orderid);
this.setShopname(shopname);
this.setOwnername(ownername);
this.setMobile(mobile);
this.setLocation(location);
this.setItemscount(itemscount);
this.setAmount(amount);
this.setApproval(Approval);
this.setDecline(Decline);
}
public String getDate()
{
return date;
}
public static Button getApproval() {
return Approval;
}
public static void setApproval(Button approval) {
Approval = approval;
}
public static Button getDecline() {
return Decline;
}
public static void setDecline(Button decline) {
Decline = decline;
}
public void setDate(String date) {
this.date = date;
}
public String getOrderid() {
return orderid;
}
public void setOrderid(String orderid) {
this.orderid = orderid;
}
public String getShopname() {
return shopname;
}
public void setShopname(String shopname) {
this.shopname = shopname;
}
public String getOwnername() {
return ownername;
}
public void setOwnername(String ownername) {
this.ownername = ownername;
}
public String getMobile() {
return mobile;
}
public void setMobile(String mobile) {
this.mobile = mobile;
}
public String getLocation() {
return location;
}
public void setLocation(String location) {
this.location = location;
}
public String getItemscount() {
return itemscount;
}
public void setItemscount(String itemscount) {
this.itemscount = itemscount;
}
public String getAmount() {
return amount;
}
public void setAmount(String amount) {
this.amount = amount;
}
}
Don't know where I did Mistake,Please Help me to findout that,Thanks in Advance.
You class members should never be declared static as you have done here -
public class OrderApprovalDetails
{
public static String date,orderid,shopname,ownername,mobile,location,itemscount,amount;
change this to
public class OrderApprovalDetails
{
public String date,orderid,shopname,ownername,mobile,location,itemscount,amount;
1- MainActivity:
public class MainActivity extends AppCompatActivity {
private List<String> mListItems = Arrays.asList("Hamaki","Amr Diab");
private ArtistsAdapter mAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ListView listView = (ListView)findViewById(R.id.Artist_list_view);
mAdapter = new ArtistsAdapter(this, mListItems);
listView.setAdapter(mAdapter);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Intent intent = new Intent(MainActivity.this,SoundActivity.class);
intent.putExtra("Artist", mListItems.get(position));
startActivity(intent);
}
});
}
}
2-Sound Activity:
public class SoundActivity extends AppCompatActivity {
#Override
protected void onStart() {
super.onStart();
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_sound);
if (savedInstanceState == null) {
getSupportFragmentManager().beginTransaction().add(R.id.container, new SoundFragment()).commit();
}
}
3-Sound Fragment:
public class SoundFragment extends Fragment {
static SCTrackAdapter mAdapter;
static DatabaseReference db;
static FirebaseHelper helper;
private TextView mSelectedTrackTitle;
static ArrayList<Music> mTracks = new ArrayList<>();
static MediaPlayer mMediaPlayer;
private ImageView mPlayerControl;
static String Artist;
static ListView listView;
int currentTrack;
private static String fileName;
public SoundFragment() {
// Required empty public constructor
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public void onStart() {
super.onStart();
new Fetchtracks().execute();
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_sound, container, false);
Intent intent = getActivity().getIntent();
if (intent != null) {
Artist = intent.getStringExtra("Artist");
}
listView = (ListView) rootView.findViewById(R.id.track_list_view);
mAdapter = new SCTrackAdapter(getActivity(), mTracks);
listView.setAdapter(mAdapter);
return rootView;
}
4- STrack Adapter:
public class SCTrackAdapter extends BaseAdapter {
private Context mContext;
private ArrayList<Music> mTracks;
public SCTrackAdapter(Context context, ArrayList<Music> tracks) {
mContext = context;
mTracks = tracks;
}
public void update_tracks(ArrayList<Music> list)
{
mTracks.clear();
mTracks.addAll(list);
}
#Override
public int getCount() {
return mTracks.size();
}
#Override
public Music getItem(int position) {
return mTracks.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder;
if (convertView == null) {
convertView = LayoutInflater.from(mContext).inflate(R.layout.track_list_row, parent, false);
holder = new ViewHolder();
holder.titleTextView = (TextView) convertView.findViewById(R.id.track_title);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
holder.titleTextView.setText(mTracks.get(position).getName());
return convertView;
}
static class ViewHolder {
TextView titleTextView;
}
}
5- Fetchtracks:
public class Fetchtracks extends AsyncTask<Void, Void, ArrayList<Music>> {
#Override
protected ArrayList<Music> doInBackground(Void... voids) {
db = FirebaseDatabase.getInstance().getReference().child(Artist);
helper = new FirebaseHelper(db);
mTracks.addAll(helper.retrieve());
Log.e("doInBackground: ",helper.retrieve()+"");
return mTracks;
}
#Override
protected void onPostExecute(ArrayList<Music> list) {
super.onPostExecute(list);
Log.e("doInBackground: ",list.size()+"");
mAdapter.update_tracks(list);
mAdapter.notifyDataSetChanged();
}
}
6- FirebaseHelper:
public class FirebaseHelper {
DatabaseReference db;
Boolean saved=null;
ArrayList<Music> A = new ArrayList<>();
public FirebaseHelper(DatabaseReference db) {
this.db = db;
}
//WRITE
public Boolean save(Music m)
{
if(m==null)
{
saved=false;
}else
{
try
{
// db.child(Artist).push().setValue(m);
saved=true;
}catch (DatabaseException e)
{
e.printStackTrace();
saved=false;
}
}
return saved;
}
//READ
public ArrayList<Music> retrieve()
{
A.clear();
db.addChildEventListener(new ChildEventListener() {
#Override
public void onChildAdded(DataSnapshot dataSnapshot, String s) {
Log.e("onChildAdded: ", "1");
fetchData(dataSnapshot);
}
#Override
public void onChildChanged(DataSnapshot dataSnapshot, String s) {
Log.e("onChildAdded: ", "2");
fetchData(dataSnapshot);
}
#Override
public void onChildRemoved(DataSnapshot dataSnapshot) {
// Log.e("onChildAdded: ", "3");
}
#Override
public void onChildMoved(DataSnapshot dataSnapshot, String s) {
// Log.e("onChildAdded: ", "4");
}
#Override
public void onCancelled(DatabaseError databaseError) {
// Log.e("onChildAdded: ", "5");
}
});
return A;
}
private void fetchData(DataSnapshot dataSnapshot)
{
Music m=new Music();
m.setName(dataSnapshot.child("name").getValue().toString());
m.setUrl(dataSnapshot.child("url").getValue().toString());
A.add(m);
// SoundFragment.mTracks.add(m);
// Log.e("onFetch: ", SoundFragment.mTracks.size()+"");
}
}
7- Music:
public class Music {
String name;
String url;
public Music() {
}
public void setName(String name) {
this.name = name;
}
public void setUrl(String url) {
this.url = url;
}
public String getName() {
return name;
}
public String getURL() {
return url;
}
}
no need to call this in onPostExecute() as it is only set
listView.setAdapter(mAdapter);
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 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