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.
Related
This question already has answers here:
recyclerview No adapter attached; skipping layout
(38 answers)
Closed 2 years ago.
i'm building an application that connects to my Drupal API. Somehow i'm not getting any data display within my application. I don't see any errors in the code and the debugging online gives the follow error: E/RecyclerView: No adapter attached; skipping layout
Here is my MainActivity code:
package com.example.eindopdrachtcmsapi;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextWatcher;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.TextView;
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.JsonArrayRequest;
import com.android.volley.toolbox.JsonObjectRequest;
import com.android.volley.toolbox.Volley;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.security.PrivateKey;
import java.util.ArrayList;
import java.util.LinkedList;
public class MainActivity extends AppCompatActivity implements ExampleAdapter.onItemClickListener {
public static final String EXTRA_TITLE = "title";
public static final String EXTRA_BODY = "body";
public static final String EXTRA_LINK = "link";
private RecyclerView mRecyclerView;
private ExampleAdapter mExampleAdapter;
private ArrayList<ExampleItem> mExampleList;
private RequestQueue mRequestQueue;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mRecyclerView = findViewById(R.id.recycler_view);
mRecyclerView.setLayoutManager(new LinearLayoutManager(this));
mRecyclerView.setHasFixedSize(true);
mRecyclerView.setAdapter(mExampleAdapter);
mExampleList = new ArrayList<>();
mRequestQueue = Volley.newRequestQueue(this);
parseJSON();
}
private void parseJSON() {
String url = "http://vistudio.be/api/portfolio";
JsonArrayRequest request = new JsonArrayRequest(Request.Method.GET, url, null,
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
try {
for (int i = 0; i < response.length(); i++) {
JSONObject portfolio = response.getJSONObject(i);
String title = portfolio.getString("title");
String body = portfolio.getString("body");
String link = portfolio.getString("field_website_url");
mExampleList.add(new ExampleItem(title, body, link));
}
mExampleAdapter = new ExampleAdapter(MainActivity.this, mExampleList);
mRecyclerView.setAdapter(mExampleAdapter);
mExampleAdapter.setOnClickListener(MainActivity.this, new ExampleAdapter.onItemClickListener() {
#Override
public void onItemClick(int position) {
ExampleItem clickedItem = mExampleList.get(position);
String title = clickedItem.getTitle();
String Link = clickedItem.getLink();
Intent mSharingIntent = new Intent(Intent.ACTION_SEND);
mSharingIntent.setType("text/plain");
mSharingIntent.putExtra(Intent.EXTRA_SUBJECT, "Vistudio");
mSharingIntent.putExtra(Intent.EXTRA_TEXT, title + " - "+ Link);
startActivity(Intent.createChooser(mSharingIntent, "Share"));
}
});
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
error.printStackTrace();
}
});
mRequestQueue.add(request);
}
#Override
public void onItemClick(int position) {
Intent detailIntent = new Intent(this, DetailActivity.class);
ExampleItem clickedItem = mExampleList.get(position);
detailIntent.putExtra(EXTRA_TITLE, clickedItem.getTitle());
detailIntent.putExtra(EXTRA_BODY, clickedItem.getBody());
detailIntent.putExtra(EXTRA_LINK, clickedItem.getLink());
mExampleAdapter.setOnClickListener(MainActivity.this, new ExampleAdapter.onItemClickListener() {
#Override
public void onItemClick(int position) {
ExampleItem clickedItem = mExampleList.get(position);
String title = clickedItem.getTitle();
String Link = clickedItem.getLink();
Intent mSharingIntent = new Intent(Intent.ACTION_SEND);
mSharingIntent.setType("text/plain");
mSharingIntent.putExtra(Intent.EXTRA_SUBJECT, "Vistudio");
mSharingIntent.putExtra(Intent.EXTRA_TEXT, title + " - "+ Link);
startActivity(Intent.createChooser(mSharingIntent, "Share"));
}
});
startActivity(detailIntent);
}
}
My Adapter code:
package com.example.eindopdrachtcmsapi;
import android.content.Context;
import android.graphics.PorterDuffColorFilter;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import java.util.ArrayList;
public class ExampleAdapter extends RecyclerView.Adapter<ExampleAdapter.portfolioViewHolder>{
private Context mContext;
private ArrayList<ExampleItem> mExampleList;
private onItemClickListener mListener;
private onItemClickListener mListenerShare;
public interface onItemClickListener{
void onItemClick(int position);
}
public void setOnClickListener(onItemClickListener listener, onItemClickListener listenerShare){
mListener = listener;
mListenerShare = listenerShare;
}
public ExampleAdapter(Context context, ArrayList<ExampleItem> ExampleList) {
mContext = context;
mExampleList = ExampleList;
}
#Override
public portfolioViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View v = LayoutInflater.from(mContext).inflate(R.layout.exampleitem, parent, false);
return new portfolioViewHolder(v);
}
#Override
public void onBindViewHolder(portfolioViewHolder holder, int position) {
ExampleItem currentItem = mExampleList.get(position);
String title = currentItem.getTitle();
String body = currentItem.getBody();
String link = currentItem.getLink();
holder.mTextViewTitle.setText(title);
holder.mTextViewBody.setText(body);
holder.mTextViewLink.setText(link);
}
#Override
public int getItemCount() {
return mExampleList.size();
}
public class portfolioViewHolder extends RecyclerView.ViewHolder{
public TextView mTextViewTitle;
public TextView mTextViewBody;
public TextView mTextViewLink;
public Button mButton;
public portfolioViewHolder(View itemView) {
super(itemView);
mTextViewTitle = itemView.findViewById(R.id.text_view_title);
mTextViewBody = itemView.findViewById(R.id.text_view_body);
mTextViewLink = itemView.findViewById(R.id.text_view_link);
mButton = itemView.findViewById(R.id.share);
mButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (mListenerShare != null){
int position = getAdapterPosition();
if (position != RecyclerView.NO_POSITION) {
mListenerShare.onItemClick(position);
}
}
}
});
itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (mListener != null){
int position = getAdapterPosition();
if (position != RecyclerView.NO_POSITION) {
mListener.onItemClick(position);
}
}
}
});
}
}
}
first remove inside oncreate()
mRecyclerView.setAdapter(mExampleAdapter);
after this code
mExampleAdapter = new ExampleAdapter(MainActivity.this, mExampleList);
mRecyclerView.setAdapter(mExampleAdapter);
add this:-
mExampleAdapter.notifyDataSetChanged();
So far I can't find an article that explains how to handle scraping infinite scrolling page in Android Studio's Java. Maybe I'm not good at searching or else.
I'm doing a news app project that will display news using web scraping technique, and can also fetch data from the next page.
More on here : How to crawl a website with multiple pages using java
But, now I'm facing a new problem because one of my news source using infinite scrolling method for their site -> https://www.gameinformer.com/news
So, is there any way I can fetch the news data from this website's load more button ?
In case anyone need my code, here it is :
GameInformer's main activity :
package com.example.user.newsapp;
import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import android.support.v7.widget.CardView;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.select.Elements;
import java.io.IOException;
import java.util.ArrayList;
public class News_GameInformer extends AppCompatActivity {
Toolbar toolbar;
private ProgressDialog mProgressDialog;
private String url = "https://www.gameinformer.com/news";
private ArrayList<String> mNewsTitleList = new ArrayList<>();
private ArrayList<String> mNewsDescList = new ArrayList<>();
private ArrayList<String> mNewsDateList = new ArrayList<>();
private CardView cardView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_news__game_informer);
new Description().execute();
toolbar = findViewById(R.id.toolbar_news_gameinformer);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
}
private class Description extends AsyncTask<Void,Void,Void> {
String desc;
#Override
protected void onPreExecute() {
super.onPreExecute();
mProgressDialog = new ProgressDialog(News_GameInformer.this);
mProgressDialog.setTitle("Connecting to GameInformer.com");
mProgressDialog.setMessage("Loading...");
mProgressDialog.setIndeterminate(true);
mProgressDialog.setCancelable(false);
mProgressDialog.setCanceledOnTouchOutside(false);
mProgressDialog.show();
}
#Override
protected Void doInBackground(Void... params) {
try {
Document mNewsDocument = Jsoup.connect(url).get();
Elements mElementDataSize = mNewsDocument.select("article[class=node teaser node--type-article node--promoted node--view-mode-teaser]");
int mElementSize = mElementDataSize.size();
for (int i=0;i<mElementSize;i++) {
Elements mElementNewsTitle = mNewsDocument.select("h2[class=page-title]").select("span").eq(i);
String mNewsTitle = mElementNewsTitle.text();
Elements mElementNewsDesc = mNewsDocument.select("div[class=field field--name-field-promo-summary field--type-string field--label-hidden field__item]").eq(i);
String mNewsDesc = mElementNewsDesc.text();
Elements mElementNewsDate = mNewsDocument.select("div[class=node__submitted author-details]").select("span[class=field field--name-created field--type-created field--label-hidden]").eq(i);
String mNewsDate = mElementNewsDate.text();
mNewsTitleList.add(mNewsTitle);
mNewsDescList.add(mNewsDesc);
mNewsDateList.add(mNewsDate);
}
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void result) {
RecyclerView mRecyclerView = findViewById(R.id.act_recyclerview_gi_news);
gameinformer_DataAdapter mDataAdapter = new gameinformer_DataAdapter(News_GameInformer.this, mNewsTitleList, mNewsDescList, mNewsDateList, cardView);
RecyclerView.LayoutManager mLayoutManager = new LinearLayoutManager(getApplicationContext());
mRecyclerView.setLayoutManager(mLayoutManager);
mRecyclerView.setAdapter(mDataAdapter);
mProgressDialog.dismiss();
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_main,menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id==R.id.gamezone) {
Intent i = new Intent(getApplicationContext(),News_GameZone.class);
startActivity(i);
} else if (id==R.id.gameinformer) {
Intent i = new Intent(getApplicationContext(),News_GameInformer.class);
startActivity(i);
} else if (id==R.id.gamespot) {
Intent i = new Intent(getApplicationContext(),News_GameSpot.class);
startActivity(i);
} else if (id==R.id.pcgamer) {
Intent i = new Intent(getApplicationContext(),News_PCGamer.class);
startActivity(i);
} else if (id==android.R.id.home) {
finish();
} else if (id==R.id.menuinfo) {
Intent i = new Intent(getApplicationContext(),Info.class);
startActivity(i);
} else if (id==R.id.menupeople) {
Intent i = new Intent(getApplicationContext(),People.class);
startActivity(i);
}
return super.onOptionsItemSelected(item);
}
}
Data Adapter's code :
package com.example.user.newsapp;
import android.app.Activity;
import android.content.Intent;
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.TextView;
import java.util.ArrayList;
public class gameinformer_DataAdapter extends RecyclerView.Adapter<gameinformer_DataAdapter.MyViewHolder> {
private ArrayList<String> mNewsTitleList = new ArrayList<>();
private ArrayList<String> mNewsDescList = new ArrayList<>();
private ArrayList<String> mNewsDateList = new ArrayList<>();
private Activity mActivity;
private int lastPosition=-1;
private CardView cardView;
public gameinformer_DataAdapter (News_GameInformer activity, ArrayList<String> mNewsTitleList, ArrayList<String> mNewsDescList, ArrayList<String> mNewsDateList, CardView cardView) {
this.mActivity = activity;
this.mNewsTitleList = mNewsTitleList;
this.mNewsDescList = mNewsDescList;
this.mNewsDateList = mNewsDateList;
this.cardView = cardView;
}
public class MyViewHolder extends RecyclerView.ViewHolder {
private TextView gameinformer_news_title, gameinformer_news_desc, gameinformer_news_date;
private CardView cardView_layout;
public MyViewHolder(View view) {
super(view);
gameinformer_news_title = view.findViewById(R.id.row_gi_news_title);
gameinformer_news_desc = view.findViewById(R.id.row_gi_news_desc);
gameinformer_news_date = view.findViewById(R.id.row_gi_news_date);
cardView_layout = view.findViewById(R.id.gi_cardview);
}
}
#Override
public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View itemView = LayoutInflater.from(parent.getContext())
.inflate(R.layout.gameinformer_row_data,parent,false);
return new MyViewHolder(itemView);
}
#Override
public void onBindViewHolder(MyViewHolder holder, final int position) {
holder.gameinformer_news_title.setText(mNewsTitleList.get(position));
holder.gameinformer_news_desc.setText(mNewsDescList.get(position));
holder.gameinformer_news_date.setText(mNewsDateList.get(position));
holder.cardView_layout.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String title = mNewsTitleList.get(position);
Intent i = new Intent(mActivity, News_GameInformer_Webview.class);
i.putExtra("keytitle",title);
mActivity.startActivity(i);
}
});
}
#Override
public int getItemCount() {
return mNewsTitleList.size();
}
}
Currently, I'm developing a media player, and I want hide a element when audio finishes. But when it happens, the app crash with this error: Attempt to invoke virtual method 'void android.widget.LinearLayout.setVisibility(int)' on a null object reference. Check my current code:
meplayer.java
package etes.xddda.music;
import android.app.Activity;
import android.content.Context;
import android.media.MediaPlayer;
import android.net.Uri;
import android.os.Bundle;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.Toast;
public class meplayer extends Activity {
public static MediaPlayer mediaPlayer;
public LinearLayout menu_dialog;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
menu_dialog = findViewById(R.id.menu_dialog);
}
public void initAudio(final Context context, final String url) {
if (mediaPlayer == null) {
mediaPlayer = MediaPlayer.create(context, Uri.parse(url));
}
mediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
public LinearLayout menu_dialog;
#Override
public void onCompletion(MediaPlayer mp) {
//Toast.makeText(context, "TEST", Toast.LENGTH_LONG).show();
killMediaPlayer();
menu_dialog.setVisibility(View.GONE);
}
});
mediaPlayer.start();
}
private void killMediaPlayer() {
if (mediaPlayer != null) {
try {
mediaPlayer.reset();
mediaPlayer.release();
mediaPlayer = null;
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
RecyclerViewAdapter
package etes.xddda.music;
import android.app.Dialog;
import android.content.Context;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.media.MediaPlayer;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import java.util.List;
public class RecyclerViewAdapter extends RecyclerView.Adapter<RecyclerViewAdapter.MyViewHolder> implements View.OnClickListener{
Context mContext;
List<mList> mData;
Dialog myDialog;
private MediaPlayer mediaPlayer;
private int playbackPosition=0;
meplayer media;
private LinearLayout menu_dialog;
public RecyclerViewAdapter(Context mContext, List<mList> mData) {
this.mContext = mContext;
this.mData = mData;
}
public void onClick(View view) {
}
#Override
public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View v;
v = LayoutInflater.from(mContext).inflate(R.layout.item_list, parent, false);
final MyViewHolder vHolder = new MyViewHolder(v);
// Dialog ini
myDialog = new Dialog(mContext);
myDialog.setContentView(R.layout.dialog);
myDialog.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
vHolder.item_play.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v)
{
TextView dialog_name_tv = (TextView) myDialog.findViewById(R.id.dialog_name_id);
TextView dialog_phone_tv = (TextView) myDialog.findViewById(R.id.dialog_author_id);
ImageView dialog_contact_img = (ImageView) myDialog.findViewById(R.id.dialog_img);
dialog_name_tv.setText(mData.get(vHolder.getAdapterPosition()).getName());
dialog_phone_tv.setText(mData.get(vHolder.getAdapterPosition()).getPhone());
dialog_contact_img.setImageResource(mData.get(vHolder.getAdapterPosition()).getPhoto());
//Toast.makeText(mContext, "Test click "+String.valueOf(vHolder.getAdapterPosition()), Toast.LENGTH_SHORT).show();
myDialog.show();
}
});
vHolder.menu_play.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v)
{
menu_dialog = v.getRootView().findViewById(R.id.menu_dialog);
menu_dialog.setVisibility(v.VISIBLE);
media = new meplayer();
media.initAudio(v.getContext(), mData.get(vHolder.getAdapterPosition()).getURL());
MainActivity.setMargins(v.getRootView().findViewById(R.id.viewpager_id), 0,0,0,100);
}
});
return vHolder;
}
#Override
public void onBindViewHolder(MyViewHolder holder, int position) {
holder.tv_name.setText(mData.get(position).getName());
holder.tv_author.setText(mData.get(position).getPhone());
holder.img.setImageResource(mData.get(position).getPhoto());
}
#Override
public int getItemCount() {
return mData.size();
}
public static class MyViewHolder extends RecyclerView.ViewHolder {
private ImageButton item_play;
private LinearLayout menu_play;
private TextView tv_name;
private TextView tv_author;
private TextView tv_url;
private ImageView img;
public MyViewHolder(View itemView) {
super(itemView);
item_play = itemView.findViewById(R.id.info_id);
menu_play = itemView.findViewById(R.id.list_item_id);
tv_name = (TextView) itemView.findViewById(R.id.name_list);
tv_author = (TextView) itemView.findViewById(R.id.author_list);
img = (ImageView) itemView.findViewById(R.id.img_contact);
}
}
}
fragmentList
package etes.xddda.music;
import android.support.v4.app.Fragment;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
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;
public class fragmentList extends Fragment {
View v;
private RecyclerView myrecyclerview;
private List<mList> lstContact;
private String URL_JSON = "https://pastebin.com/raw/fG3zd40U";
private JsonArrayRequest ArrayRequest;
private RequestQueue requestQueue ;
public fragmentList() {
}
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
v = inflater.inflate(R.layout.list_fragment,container,false);
myrecyclerview = (RecyclerView) v.findViewById(R.id.list_recyclerview);
RecyclerViewAdapter recyclerViewAdapter = new RecyclerViewAdapter(getContext(), lstContact);
myrecyclerview.setLayoutManager(new LinearLayoutManager(getActivity()));
myrecyclerview.setAdapter(recyclerViewAdapter);
return v;
}
#Override
public void onCreate(#Nullable Bundle savedInstaceState) {
super.onCreate(savedInstaceState);
_JSONcall();
}
public void _JSONcall() {
lstContact = new ArrayList<>();
ArrayRequest = new JsonArrayRequest(URL_JSON, new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
JSONObject jsonObject = null;
for (int i = 0 ; i<response.length();i++) {
try {
jsonObject = response.getJSONObject(i);
lstContact.add(new mList(jsonObject.getString("name"), jsonObject.getString("description"), jsonObject.getString("link"), R.drawable.ic_play_circle_filled_black_24dp));
}
catch (JSONException e) {
e.printStackTrace();
Toast.makeText(getActivity(), "Error 1!",
Toast.LENGTH_LONG).show();
}
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(getActivity(), "Error 3!",
Toast.LENGTH_LONG).show();
}
});
requestQueue = Volley.newRequestQueue(getActivity().getApplicationContext());
requestQueue.add(ArrayRequest);
}
}
MainActivity
package etes.xddda.music;
import android.annotation.SuppressLint;
import android.support.design.widget.TabLayout;
import android.support.v4.view.ViewPager;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageButton;
import android.widget.LinearLayout;
public class MainActivity extends AppCompatActivity {
private DrawerLayout nDrawerLayout;
private ActionBarDrawerToggle mToggle;
private TabLayout tabLayout;
private ViewPager viewPager;
private viewPagerAdapter adapter;
public LinearLayout menu_dialog;
private String player_status = "playing";
private ImageButton player_img;
#SuppressLint("RestrictedApi")
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
nDrawerLayout = findViewById(R.id.drawer);
menu_dialog = findViewById(R.id.menu_dialog);
menu_dialog.setVisibility(View.GONE);
player_img = findViewById(R.id.playorpause);
player_img.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
//setMargins(viewPager, 0,0,0,110);
if (player_status == "playing") {
player_img.setImageResource(R.drawable.ic_play_arrow_black_24dp);
meplayer.pauseAudio();
player_status = "paused";
} else {
player_img.setImageResource(R.drawable.ic_pause_black_24dp);
meplayer.startAudio();
player_status = "playing";
}
}
});
//menu_dialog.setLayoutParams(new LinearLayout.LayoutParams(0, 0));
mToggle = new ActionBarDrawerToggle(this, nDrawerLayout, R.string.open, R.string.close);
nDrawerLayout.addDrawerListener(mToggle);
getSupportActionBar().setDefaultDisplayHomeAsUpEnabled(true);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
tabLayout = findViewById(R.id.tablayout_id);
viewPager = findViewById(R.id.viewpager_id);
//viewPager.setLayoutParams(new ViewPager.LayoutParams(0, 0));
//setMarginBottom(viewPager, 0);
setMargins(viewPager, 0,0,0,0);
adapter = new viewPagerAdapter(getSupportFragmentManager());
//Add fragments here
adapter.addFragment(new fragmentList(), ""); //Lista de música
adapter.addFragment(new fragmentFrequent(), ""); //Frequentes
adapter.addFragment(new fragmentPlayList(), ""); //Playlist
viewPager.setAdapter(adapter);
tabLayout.setupWithViewPager(viewPager);
tabLayout.getTabAt(0).setIcon(R.drawable.ic_music_note_black_24dp); //Lista de música
tabLayout.getTabAt(1).setIcon(R.drawable.ic_filter_list_black_24dp); // Frequentes
tabLayout.getTabAt(2).setIcon(R.drawable.ic_queue_music_black_24dp); // Playlist
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if (mToggle.onOptionsItemSelected(item)) {
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
protected void onPostCreate(Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
// Sync the toggle state after onRestoreInstanceState has occurred.
mToggle.syncState();
}
public static void setMargins (View v, int l, int t, int r, int b) {
if (v.getLayoutParams() instanceof ViewGroup.MarginLayoutParams) {
ViewGroup.MarginLayoutParams p = (ViewGroup.MarginLayoutParams) v.getLayoutParams();
p.setMargins(l, t, r, b);
v.requestLayout();
}
}
}
mList
package etes.xddda.music;
public class mList {
private String Name;
private String Author;
private String URL;
private int Photo;
public mList() {
}
public mList(String name, String phone, String url, int photo) {
Name = name;
Author = phone;
URL = url;
Photo = photo;
}
//Get User
public String getName() {
return Name;
}
public String getPhone() {
return Author;
}
public String getURL() {
return URL;
}
public int getPhoto() {
return Photo;
}
//Setter
public void setName(String name) {
Name = name;
}
public void setPhone(String phone) {
Author = phone;
}
public void setURL(String url) {
URL = url;
}
public void setPhoto(int photo) {
Photo = photo;
}
}
There are no errors in this script, the app just crash when audio finishes. The problem is related to line menu_dialog.setVisibility(View.GONE); and I have already defined menu_dialog in onCreate. So, can you help me?
P.S.: menu_dialog belongs to activity_main.xml
Thank you!
Remove the local variable menu_dialog that you have defined inside the OnCompletionListener:
package etes.xddda.music;
import android.app.Activity;
import android.content.Context;
import android.media.MediaPlayer;
import android.net.Uri;
import android.os.Bundle;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.Toast;
public class meplayer extends Activity {
public static MediaPlayer mediaPlayer;
public LinearLayout menu_dialog;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
menu_dialog = findViewById(R.id.menu_dialog);
}
public void initAudio(final Context context, final String url) {
if (mediaPlayer == null) {
mediaPlayer = MediaPlayer.create(context, Uri.parse(url));
}
mediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
//public LinearLayout menu_dialog; REMOVE THIS
#Override
public void onCompletion(MediaPlayer mp) {
//Toast.makeText(context, "TEST", Toast.LENGTH_LONG).show();
killMediaPlayer();
menu_dialog.setVisibility(View.GONE);
}
});
mediaPlayer.start();
}
private void killMediaPlayer() {
if (mediaPlayer != null) {
try {
mediaPlayer.reset();
mediaPlayer.release();
mediaPlayer = null;
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 4 years ago.
I'm spending the last 5 days trying solve this problem. I really do not have any idea about how to solve it. I'm getting Attempt to invoke virtual method 'android.view.Window$Callback android.view.Window.getCallback()' on a null object reference. Check my code:
RecyclerView.java
package etes.xdda.music;
import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.media.MediaPlayer;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import java.util.List;
public class RecyclerViewAdapter extends RecyclerView.Adapter<RecyclerViewAdapter.MyViewHolder> implements View.OnClickListener{
Context mContext;
List<mList> mData;
Dialog myDialog;
private MediaPlayer mediaPlayer;
private int playbackPosition=0;
private LinearLayout menu_dialog;
public RecyclerViewAdapter(Context mContext, List<mList> mData) {
this.mContext = mContext;
this.mData = mData;
}
public void onClick(View view) {
}
#Override
public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View v;
v = LayoutInflater.from(mContext).inflate(R.layout.item_list, parent, false);
final MyViewHolder vHolder = new MyViewHolder(v);
// Dialog ini
myDialog = new Dialog(mContext);
myDialog.setContentView(R.layout.dialog);
myDialog.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
vHolder.item_play.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v)
{
TextView dialog_name_tv = (TextView) myDialog.findViewById(R.id.dialog_name_id);
TextView dialog_phone_tv = (TextView) myDialog.findViewById(R.id.dialog_author_id);
ImageView dialog_contact_img = (ImageView) myDialog.findViewById(R.id.dialog_img);
dialog_name_tv.setText(mData.get(vHolder.getAdapterPosition()).getName());
dialog_phone_tv.setText(mData.get(vHolder.getAdapterPosition()).getPhone());
dialog_contact_img.setImageResource(mData.get(vHolder.getAdapterPosition()).getPhoto());
//Toast.makeText(mContext, "Test click "+String.valueOf(vHolder.getAdapterPosition()), Toast.LENGTH_SHORT).show();
myDialog.show();
}
});
vHolder.menu_play.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v)
{
menu_dialog = v.getRootView().findViewById(R.id.menu_dialog);
menu_dialog.setVisibility(v.VISIBLE);
MainActivity a = new MainActivity();
a.initAudio(v.getContext(), mData.get(vHolder.getAdapterPosition()).getURL());
MainActivity.setMargins(v.getRootView().findViewById(R.id.viewpager_id), 0,0,0,100);
}
});
return vHolder;
}
#Override
public void onBindViewHolder(MyViewHolder holder, int position) {
holder.tv_name.setText(mData.get(position).getName());
holder.tv_author.setText(mData.get(position).getPhone());
holder.img.setImageResource(mData.get(position).getPhoto());
}
#Override
public int getItemCount() {
return mData.size();
}
public static class MyViewHolder extends RecyclerView.ViewHolder {
private ImageButton item_play;
private LinearLayout menu_play;
private TextView tv_name;
private TextView tv_author;
private TextView tv_url;
private ImageView img;
public MyViewHolder(View itemView) {
super(itemView);
item_play = itemView.findViewById(R.id.info_id);
menu_play = itemView.findViewById(R.id.list_item_id);
tv_name = (TextView) itemView.findViewById(R.id.name_list);
tv_author = (TextView) itemView.findViewById(R.id.author_list);
img = (ImageView) itemView.findViewById(R.id.img_contact);
}
}
}
Note that I'm invoking MainActivity.java in this part:
vHolder.menu_play.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v)
{
menu_dialog = v.getRootView().findViewById(R.id.menu_dialog);
menu_dialog.setVisibility(v.VISIBLE);
MainActivity a = new MainActivity();
a.initAudio(v.getContext(), mData.get(vHolder.getAdapterPosition()).getURL());
MainActivity.setMargins(v.getRootView().findViewById(R.id.viewpager_id), 0,0,0,100);
}
});
And here's my MainActivity.java
package etes.xdda.music;
import android.annotation.SuppressLint;
import android.content.Context;
import android.media.MediaPlayer;
import android.net.Uri;
import android.support.design.widget.TabLayout;
import android.support.v4.view.ViewPager;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageButton;
import android.widget.LinearLayout;
public class MainActivity extends AppCompatActivity {
private DrawerLayout nDrawerLayout;
private ActionBarDrawerToggle mToggle;
private TabLayout tabLayout;
private ViewPager viewPager;
private viewPagerAdapter adapter;
public LinearLayout menu_dialog;
private String player_status = "playing";
private ImageButton player_img;
private static MediaPlayer mediaPlayer;
#SuppressLint("RestrictedApi")
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
nDrawerLayout = findViewById(R.id.drawer);
menu_dialog = findViewById(R.id.menu_dialog);
menu_dialog.setVisibility(View.GONE);
player_img = findViewById(R.id.playorpause);
player_img.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
//setMargins(viewPager, 0,0,0,110);
if (player_status == "playing") {
player_img.setImageResource(R.drawable.ic_play_arrow_black_24dp);
meplayer.pauseAudio();
player_status = "paused";
} else {
player_img.setImageResource(R.drawable.ic_pause_black_24dp);
meplayer.startAudio();
player_status = "playing";
}
}
});
//menu_dialog.setLayoutParams(new LinearLayout.LayoutParams(0, 0));
mToggle = new ActionBarDrawerToggle(this, nDrawerLayout, R.string.open, R.string.close);
nDrawerLayout.addDrawerListener(mToggle);
getSupportActionBar().setDefaultDisplayHomeAsUpEnabled(true);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
tabLayout = findViewById(R.id.tablayout_id);
viewPager = findViewById(R.id.viewpager_id);
//viewPager.setLayoutParams(new ViewPager.LayoutParams(0, 0));
//setMarginBottom(viewPager, 0);
setMargins(viewPager, 0,0,0,0);
adapter = new viewPagerAdapter(getSupportFragmentManager());
//Add fragments here
adapter.addFragment(new fragmentList(), ""); //Lista de música
adapter.addFragment(new fragmentFrequent(), ""); //Frequentes
adapter.addFragment(new fragmentPlayList(), ""); //Playlist
viewPager.setAdapter(adapter);
tabLayout.setupWithViewPager(viewPager);
tabLayout.getTabAt(0).setIcon(R.drawable.ic_music_note_black_24dp); //Lista de música
tabLayout.getTabAt(1).setIcon(R.drawable.ic_filter_list_black_24dp); // Frequentes
tabLayout.getTabAt(2).setIcon(R.drawable.ic_queue_music_black_24dp); // Playlist
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if (mToggle.onOptionsItemSelected(item)) {
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
protected void onPostCreate(Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
// Sync the toggle state after onRestoreInstanceState has occurred.
mToggle.syncState();
}
public static void setMargins (View v, int l, int t, int r, int b) {
if (v.getLayoutParams() instanceof ViewGroup.MarginLayoutParams) {
ViewGroup.MarginLayoutParams p = (ViewGroup.MarginLayoutParams) v.getLayoutParams();
p.setMargins(l, t, r, b);
v.requestLayout();
}
}
public void initAudio(final Context context, final String url) {
if (mediaPlayer == null) {
mediaPlayer = MediaPlayer.create(context, Uri.parse(url));
}
mediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer mp) {
//Toast.makeText(context, "TEST", Toast.LENGTH_LONG).show();
killMediaPlayer();
updateLayout();
}
});
mediaPlayer.start();
}
private static void killMediaPlayer() {
if (mediaPlayer != null) {
try {
mediaPlayer.reset();
mediaPlayer.release();
mediaPlayer = null;
} catch (Exception e) {
e.printStackTrace();
}
}
}
private void updateLayout() {
try {
menu_dialog = findViewById(R.id.menu_dialog);
menu_dialog.setVisibility(View.GONE);
} catch (Exception e) {
e.printStackTrace();
}
}
And the part of code that is giving crash is this:
private void updateLayout() {
try {
menu_dialog = findViewById(R.id.menu_dialog);
menu_dialog.setVisibility(View.GONE);
} catch (Exception e) {
e.printStackTrace();
}
}
#edit: I have added this piece of code, I don't know if can help
fragmentList.java
package etes.xdda.music;
import android.support.v4.app.Fragment;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
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;
public class fragmentList extends Fragment {
View v;
private RecyclerView myrecyclerview;
private List<mList> lstContact;
private String URL_JSON = "https://pastebin.com/raw/fG3zd40U";
private JsonArrayRequest ArrayRequest;
private RequestQueue requestQueue ;
MainActivity activity;
public fragmentList() {
}
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
v = inflater.inflate(R.layout.list_fragment,container,false);
myrecyclerview = (RecyclerView) v.findViewById(R.id.list_recyclerview);
RecyclerViewAdapter recyclerViewAdapter = new RecyclerViewAdapter(activity, lstContact);
myrecyclerview.setLayoutManager(new LinearLayoutManager(getActivity()));
myrecyclerview.setAdapter(recyclerViewAdapter);
return v;
}
#Override
public void onCreate(#Nullable Bundle savedInstaceState) {
super.onCreate(savedInstaceState);
_JSONcall();
}
public void _JSONcall() {
lstContact = new ArrayList<>();
ArrayRequest = new JsonArrayRequest(URL_JSON, new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
JSONObject jsonObject = null;
for (int i = 0 ; i<response.length();i++) {
try {
jsonObject = response.getJSONObject(i);
lstContact.add(new mList(jsonObject.getString("name"), jsonObject.getString("description"), jsonObject.getString("link"), R.drawable.ic_play_circle_filled_black_24dp));
}
catch (JSONException e) {
e.printStackTrace();
Toast.makeText(getActivity(), "Error 1!",
Toast.LENGTH_LONG).show();
}
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(getActivity(), "Error 3!",
Toast.LENGTH_LONG).show();
}
});
requestQueue = Volley.newRequestQueue(getActivity().getApplicationContext());
requestQueue.add(ArrayRequest);
}
}
Please, help me, I have no more ideas about what I should do. Thank you
Just taking a look at your code, it looks like you are doing many things wrong. Such as this line
MainActivity a = new MainActivity();
You can't instantiate lifecycle components like Services, Activities, Fragments etc this way. Android provides you these components when you call start methods etc. The activity that is created as a result of the above line doesn't go through the lifecycle calls that an activity that is started via using startActivity. As a result, the setContentView of the activity is never called and you get this error. You have to remove this line and implement this properly and the error will go away.
Also just to add, you are actually creating a new instance of the activity when one is already running when you need to call the methods on the old instance that was started.
Edit: Try like this.
MainActivity activity;
List<mList> mData;
Dialog myDialog;
private MediaPlayer mediaPlayer;
private int playbackPosition=0;
private LinearLayout menu_dialog;
public RecyclerViewAdapter(MainActivity activity, List<mList> mData) {
this.activity = activity;
this.mData = mData;
}
And then
vHolder.menu_play.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v)
{
menu_dialog = v.getRootView().findViewById(R.id.menu_dialog);
menu_dialog.setVisibility(v.VISIBLE);
activity.initAudio(v.getContext(), mData.get(vHolder.getAdapterPosition()).getURL());
activity.setMargins(v.getRootView().findViewById(R.id.viewpager_id), 0,0,0,100);
}
});
Also remove static from the main activity functions
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