I'm making a university project in which I have a map in Android Studio where by touching two cities you have to create the path with a line.
Map_fragment class:
import android.Manifest;
import android.content.Context;
import android.graphics.Color;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.core.app.ActivityCompat;
import androidx.fragment.app.Fragment;
import com.example.natour2022.R;
import com.example.natour2022.presenter.fragment.Map_presenter;
import com.example.natour2022.utils.constants.Constants;
import com.example.natour2022.view.activity.StartActivity;
import com.google.android.gms.location.FusedLocationProviderClient;
import com.google.android.gms.location.LocationServices;
import org.osmdroid.config.Configuration;
import org.osmdroid.events.MapEventsReceiver;
import org.osmdroid.library.BuildConfig;
import org.osmdroid.util.BoundingBox;
import org.osmdroid.util.GeoPoint;
import org.osmdroid.views.MapView;
import org.osmdroid.views.overlay.MapEventsOverlay;
import org.osmdroid.views.overlay.Marker;
import org.osmdroid.views.overlay.Polyline;
import org.osmdroid.bonuspack.routing.OSRMRoadManager;
import org.osmdroid.bonuspack.routing.Road;
import org.osmdroid.bonuspack.routing.RoadManager;
import java.util.ArrayList;
public class Map_fragment extends Fragment {
private StartActivity startActivity;
private Map_presenter map_presenter;
private Button buttonCancel;
private Button buttonPublic;
public ProgressBar progressBar_Map;
private ImageButton buttonBackPlan;
private ImageButton buttonImportFileGpx;
private TextView textMapp;
private MapView mMap;
private ArrayList<GeoPoint> listaGeopoint;
private Context context;
private MapEventsReceiver receiver;
private MapEventsOverlay mapEventsOverlay;
private Polyline polyline;
private RoadManager roadManager;
public static final int PERMISSION_GRANTED = 0;
private FusedLocationProviderClient fusedLocationProviderClient;
public Map_fragment(StartActivity startActivity) {
this.startActivity = startActivity;
listaGeopoint = new ArrayList<>();
}
#Override
public void onAttach (#NonNull Context context){
super.onAttach(context);
this.context = context;
}
public StartActivity getStartActivity() {
return startActivity;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(#NotNull LayoutInflater inflater,
ViewGroup container,
Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment_map, container, false);
}
#Override
public void onViewCreated(#NonNull final View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
textMapp = view.findViewById(R.id.fragment_map_textView_map);
mMap = view.findViewById(R.id.mapview);
mMap.setScrollableAreaLimitDouble(new BoundingBox(85, 180, -85, -180));
mMap.setMaxZoomLevel(18.0);
mMap.setMinZoomLevel(4.0);
mMap.setHorizontalMapRepetitionEnabled(false);
mMap.setVerticalMapRepetitionEnabled(false);
mMap.setScrollableAreaLimitLatitude(MapView.getTileSystem().getMaxLatitude(), MapView.getTileSystem().getMinLatitude(), 0);
mMap.setTileSource(TileSourceFactory.MAPNIK);
mMap.setClickable(true);
mMap.setMultiTouchControls(true);
mMap.getZoomController().setVisibility(CustomZoomButtonsController.Visibility.ALWAYS);
buttonCancel = view.findViewById(R.id.fragment_map_button_cancel);
buttonPublic = view.findViewById(R.id.fragment_map_button_public);
buttonBackPlan = view.findViewById(R.id.btBack_Map);
buttonImportFileGpx = requireActivity().findViewById(R.id.btImport_GPX);
progressBar_Map = view.findViewById(R.id.progressBar_Map);
map_presenter = new Map_presenter(this);
Configuration.getInstance().setUserAgentValue(BuildConfig.APPLICATION_ID);
fusedLocationProviderClient = LocationServices.getFusedLocationProviderClient(context);
initializeUserInterface();
getLocation();
listenToClickEvents();
}
private void initializeUserInterface() {
textMapp.setAlpha(0.0f);
mMap.setAlpha(0.0f);
buttonCancel.setAlpha(0.0f);
buttonPublic.setAlpha(0.0f);
buttonBackPlan.setAlpha(0.0f);
buttonImportFileGpx.setAlpha(0.0f);
textMapp.animate().alpha(1.0f).setDuration(7500);
mMap.animate().alpha(1.0f).setDuration(8000);
buttonCancel.animate().alpha(1.0f).setDuration(8500);
buttonPublic.animate().alpha(1.0f).setDuration(9000);
buttonBackPlan.animate().alpha(1.0f).setDuration(9500);
buttonImportFileGpx.animate().alpha(1.0f).setDuration(10000);
}
private void listenToClickEvents() {
buttonPublic.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
map_presenter.onButtonPublicClicked();
}
});
buttonCancel.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
map_presenter.onButtonCancelClicked();
}
});
buttonBackPlan.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
map_presenter.onButtonBackPlanClicked();
}
});
buttonImportFileGpx.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
map_presenter.onButtonImportFileGpxClicked();
}
});
}
private void getLocation(){
int checkFineLocation = ActivityCompat.checkSelfPermission(context, Manifest.permission.ACCESS_FINE_LOCATION);
int checkCoarseLocation = ActivityCompat.checkSelfPermission(context, Manifest.permission.ACCESS_COARSE_LOCATION);
if((checkFineLocation == PERMISSION_GRANTED) && (checkCoarseLocation == PERMISSION_GRANTED)){
fusedLocationProviderClient.getLastLocation().addOnSuccessListener(requireActivity(), location -> {
if (location != null) {
selectGeoPoints(location.getLatitude(), location.getLongitude());
} else {
Toast.makeText(getActivity(), "Non è stato possibile ottenere la tua posizione\n" +
"Controlla di avere abilitato i permessi e il GPS", Toast.LENGTH_SHORT).show();
}
});
}
}
private void selectGeoPoints(Double latitudine, Double longitudine) {
// Posizione corrente
GeoPoint point = new GeoPoint(latitudine, longitudine);
mMap.getController().setCenter(point);
receiver = new MapEventsReceiver() {
#Override
public boolean singleTapConfirmedHelper(GeoPoint p) {
if (listaGeopoint.size() < 2) {
listaGeopoint.add(p);
Marker marker = new Marker(mMap);
marker.setPosition(p);
marker.setTitle(
getResources().getString(R.string.Latitudine) + p.getLatitude() + "\n" +
getResources().getString(R.string.Longitudine) + p.getLongitude());
mMap.getOverlays().add(marker);
}
if (listaGeopoint.size() == 2) {
new Thread(() -> {
roadManager = new OSRMRoadManager(context, null);
Road percorso = roadManager.getRoad(listaGeopoint);
if (percorso.mStatus == Road.STATUS_OK) {
polyline = RoadManager.buildRoadOverlay(percorso, Color.RED, 3.0f);
mMap.getOverlays().add(polyline);
}
}).start();
}
return false;
}
#Override
public boolean longPressHelper(GeoPoint p) {
Toast.makeText(getActivity(), "Per selezionare il punto desiderato,utilizza un singolo tocco", Toast.LENGTH_SHORT).show();
return false;
}
};
mapEventsOverlay = new MapEventsOverlay(receiver);
mMap.getOverlays().add(mapEventsOverlay);
}
}
`Map_present` class:
import android.content.Context;
import android.content.Intent;
import android.widget.Toast;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentTransaction;
import com.example.natour2022.R;
import com.example.natour2022.view.activity.StartActivity;
import com.example.natour2022.view.fragment.Map_fragment;
import com.example.natour2022.view.fragment.Plan_fragment;
import com.google.android.gms.location.FusedLocationProviderClient;
import org.osmdroid.util.GeoPoint;
import java.util.ArrayList;
public class Map_presenter {
private final Map_fragment map_fragment;
private StartActivity startActivity;
private ArrayList<GeoPoint> listaGeopoint;
private Context context;
private FusedLocationProviderClient fusedLocationProviderClient;
public Map_presenter(Map_fragment map_fragment) {
this.map_fragment = map_fragment;
}
public void onButtonCancelClicked() {
Fragment fragment = new Map_fragment(startActivity);
FragmentManager fragmentManager = map_fragment.getActivity().getSupportFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.setCustomAnimations(R.anim.fade_in, R.anim.fade_out);
fragmentTransaction.replace(R.id.activity_sing_in_sing_up, fragment).commit();
}
public void onButtonBackPlanClicked() {
Fragment fragment = new Plan_fragment(startActivity);
FragmentManager fragmentManager = map_fragment.getActivity().getSupportFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.setCustomAnimations(R.anim.fade_in, R.anim.fade_out);
fragmentTransaction.replace(R.id.activity_sing_in_sing_up, fragment).commit();
}
public void onButtonImportFileGpxClicked() {
Intent selectFileGPX = new Intent();
selectFileGPX.setType("application/gpx");
selectFileGPX.addCategory(Intent.CATEGORY_OPENABLE);
selectFileGPX.putExtra(Intent.EXTRA_MIME_TYPES, "application/gpx");
selectFileGPX.setAction(Intent.ACTION_GET_CONTENT);
if (selectFileGPX.resolveActivity(map_fragment.getActivity().getPackageManager()) != null) {
map_fragment.startActivity(Intent.createChooser(selectFileGPX, "Select file GPX"));
}
}
//aggiunge tracciato all'itinerario
public void onButtonPublicClicked() {
if ((listaGeopoint.isEmpty()) || (listaGeopoint.size() < 2)) {
Toast.makeText(map_fragment.getActivity(), "Per confermare è necessario selezionare prima il punto di inizio e il punto di fine del percorso", Toast.LENGTH_SHORT).show();
} else {
// Prima coppia della lista geopoint costituita da {[LONGITUDINE, LATITUDINE], [LONGITUDINE, LATITUDINE]}
Double puntoDiInizioLongitudine = listaGeopoint.get(0).getLongitude();
Double puntoDiInizioLatitudine = listaGeopoint.get(0).getLatitude();
// Seconda coppia
Double puntoDiFineLongitudine = listaGeopoint.get(1).getLongitude();
Double puntoDiFineLatitudine = listaGeopoint.get(1).getLatitude();
//AGGIUNGO PUNTI AL DATABASE FIREBASE
}
}
}
Error: java.lang.NullPointerException: Attempt to invoke virtual method 'boolean java.util.ArrayList.isEmpty()' on a null object reference
I did this. It doesn't give me errors but it doesn't create the path. How can I do it?
Related
I have a project, controlling a jetski from a far with a android application using Bluetooth.
I have made 2 files:
Here is the "Peripherique.java" (the Bluetooth thing):
package com.example.btjetski;
import androidx.appcompat.app.AppCompatActivity;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import java.util.ArrayList;
import java.util.Set;
public class Peripherique extends AppCompatActivity {
Button btnPaired;
ListView devicelist;
private BluetoothAdapter myBluetooth;
private Set<BluetoothDevice> pairedDevices;
public static String EXTRA_ADDRESS = "device_address";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btnPaired = findViewById(R.id.button);
devicelist = findViewById(R.id.listView);
myBluetooth = BluetoothAdapter.getDefaultAdapter();
if (myBluetooth == null) {
Toast.makeText(getApplicationContext(), "Périphérique Bluetooth non disponible", Toast.LENGTH_LONG).show();
finish();
} else if (!myBluetooth.isEnabled()) {
Intent turnBTon = new
Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(turnBTon, 1);
}
btnPaired.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
list();
}
});
}
private void list() { // écouter les périphériques BT
pairedDevices = myBluetooth.getBondedDevices();
ArrayList list = new ArrayList();
if (pairedDevices.size() > 0) {
for (BluetoothDevice bt : pairedDevices) {
list.add(bt.getName() + "\n" + bt.getAddress());
}
} else {
Toast.makeText(getApplicationContext(), "Aucun des appareils trouvés", Toast.LENGTH_LONG).show();
}
ArrayAdapter adapter = new ArrayAdapter(this, android.R.layout.simple_list_item_1, list);
devicelist.setAdapter(adapter);
}
public void onItemClick(AdapterView<?> av, View v, int arg2, long arg3)
{
String info = ((TextView) v).getText().toString();
String address = info.substring(info.length() - 17);
Intent i = new Intent(Peripherique.this, jetControl.class);
i.putExtra(EXTRA_ADDRESS, address);
startActivity(i);
}
}
Here is jetControl.java
package com.example.btjetski;
import android.app.ProgressDialog;
import android.os.Bundle;
import androidx.appcompat.app.AppCompatActivity;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothSocket;
import android.content.Intent;
import android.view.View;
import android.widget.Button;
import java.io.IOException;
import java.util.UUID;
public class jetControl extends AppCompatActivity {
Button buttonON1, buttonOFF1;
String address = null;
private ProgressDialog progress;
BluetoothAdapter myBluetooth = null;
BluetoothSocket btSocket = null;
private boolean isBtConnected = false;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Intent newint = getIntent();
address = newint.getStringExtra(Peripherique.EXTRA_ADDRESS); //recevoir l'adresse du périphérique BT
setContentView(R.layout.activity_jet_control);
//WIDGETS
Button buttonON1 = findViewById(R.id.buttonON1);
Button buttonOFF1 = findViewById(R.id.buttonOFF1);
setOnClickListener();
}
private void setOnClickListener() {
buttonON1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
AllumerJetski1();
}
});
buttonOFF1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
EteindreJetski1();
}
});
}
private void AllumerJetski1() {
if (btSocket != null) {
try {
btSocket.getOutputStream().write("A".toString().getBytes());
} catch (IOException e) {
}
}
}
private void EteindreJetski1() {
if (btSocket != null) {
try {
btSocket.getOutputStream().write("a".toString().getBytes());
} catch (IOException e) {
}
}
}
}
When the app starts, i can connect to my ESP32 but nothing happens, i should have an overlay that shows up with two buttons "ON/OFF" but nothing seems to work properly.
I thank you so much for your help.
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();
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
How i have said in my question i have a fragment with a list of check boxes and an ArrayList of items choosen (they are the labels of the check boxes). When the event of a check box is fired the fragment calls the method of the interface in the main activity but in it the list of items choosen has already the item in it, although there isn't in the entire code any method that can add items to it.
Here the code:
MainActivity :
package com.fp.testfragment1;
import java.util.ArrayList;
import android.app.Activity;
import android.app.FragmentManager;
import android.app.FragmentTransaction;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.FrameLayout;
import com.fp.testfragment1.MultiChoiceFragment.OnMultiSelectedListener;
public class MainActivity extends Activity implements OnMultiSelectedListener
{
FrameLayout frameLayout1;
FrameLayout frameLayout2;
Button transitionButton;
FragmentManager fragmentManager;
MultiChoiceFragment multiChoiceFragment;
Boolean replace;
ArrayList<String> list;
ArrayList<String> mylis;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
list = new ArrayList<String>();
mylis = new ArrayList<String>();
list.add("item1");
list.add("item2");
list.add("item3");
list.add("item4");
list.add("item5");
transitionButton = (Button)findViewById(R.id.transitionButton);
transitionButton.setOnClickListener(transitionListener);
frameLayout1 = (FrameLayout)findViewById(R.id.frameLayout1);
frameLayout1 = (FrameLayout)findViewById(R.id.frameLayout2);
fragmentManager = getFragmentManager();
}
#Override
protected void onStart()
{
super.onStart();
replace = false;
}
OnClickListener transitionListener = new OnClickListener()
{
#Override
public void onClick(View v)
{
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
multiChoiceFragment = new MultiChoiceFragment(MainActivity.this, list, mylis, 8);
fragmentTransaction.setCustomAnimations(R.animator.card_flip_right_in, R.animator.card_flip_right_out, R.animator.card_flip_left_in, R.animator.card_flip_left_out);
if(replace)
{
fragmentTransaction.replace(R.id.frameLayout1, multiChoiceFragment);
}
else
{
fragmentTransaction.add(R.id.frameLayout1, multiChoiceFragment);
replace = true;
}
fragmentTransaction.addToBackStack(null);
fragmentTransaction.commit();
}
};
#Override
public void onGroupMCheckListener(String itemName, Boolean checked, int nf)
{
if(nf == 8)
{
//here i have the list already full
// this is for debug
mylis = mylis;
}
}
}
MultiChoiceFragment :
package com.fp.testfragment1;
import java.util.ArrayList;
import android.app.Activity;
import android.app.Fragment;
import android.content.Context;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.LinearLayout;
import android.widget.TableRow;
import android.widget.TextView;
public class MultiChoiceFragment extends Fragment
{
Context context;
OnMultiSelectedListener mCallback;
LinearLayout groupsListLinearLayout;
TableRow congiungiTableRow;
TextView groupsTextView;
ArrayList<String> groups;
ArrayList<String> groupsChoosen;
int nFragment;
public MultiChoiceFragment(Context context, ArrayList<String> groups, ArrayList<String> groupsChoosen, int nFragment)
{
this.context = context;
this.groups = new ArrayList<String>();
this.groupsChoosen = new ArrayList<String>();
this.groups = groups;
this.groupsChoosen = groupsChoosen;
this.nFragment = nFragment;
}
public MultiChoiceFragment()
{
groups = new ArrayList<String>();
groupsChoosen = new ArrayList<String>();
}
public interface OnMultiSelectedListener
{
public void onGroupMCheckListener(String itemName, Boolean checked, int nf);
}
#Override
public void onAttach(Activity activity)
{
super.onAttach(activity);
try
{
mCallback = (OnMultiSelectedListener) activity;
}
catch (ClassCastException e)
{
throw new ClassCastException(activity.toString() + " must implement OnMultiSelectedListener");
}
context = activity;
}
#Override
public void onSaveInstanceState(Bundle outState)
{
outState.putStringArrayList("groups", groups);
outState.putStringArrayList("groupsChoosen", groupsChoosen);
outState.putInt("nFragment", nFragment);
super.onSaveInstanceState(outState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
{
View v = inflater.inflate(R.layout.choice_fragment, container, false);
groupsListLinearLayout = (LinearLayout)v.findViewById(R.id.groupsLinearLayout);
groupsTextView = (TextView)v.findViewById(R.id.groupsTextView);
congiungiTableRow = (TableRow)v.findViewById(R.id.congiungiTableRow);
if(savedInstanceState != null)
{
groups = savedInstanceState.getStringArrayList("groups");
groupsChoosen = savedInstanceState.getStringArrayList("groupsChoosen");
nFragment = savedInstanceState.getInt("nFragment");
}
refreshListGUI();
return v;
}
public void refreshListGUI()
{
for(int a = 0; a < groups.size(); a++)
{
CheckBox checkBox = new CheckBox(context);
checkBox.setId(a);
if(groupsChoosen == null || groupsChoosen.isEmpty() == true)
{
checkBox.setChecked(false);
}
else if(groupsChoosen.isEmpty() == false && groupsChoosen.contains(groups.get(a)))
{
checkBox.setChecked(true);
}
checkBox.setText((String)groups.get(a));
checkBox.setOnCheckedChangeListener(checkBoxMItemListener);
groupsListLinearLayout.addView(checkBox);
}
}
OnCheckedChangeListener checkBoxMItemListener = new OnCheckedChangeListener()
{
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked)
{
String groupC = buttonView.getText().toString();
if(isChecked == true && groupsChoosen.contains(groupC) == false)
{
groupsChoosen.add(groupC);
mCallback.onGroupMCheckListener(groupC, isChecked, nFragment);
}
else if(isChecked == false && groupsChoosen.contains(groupC) == true)
{
groupsChoosen.remove(groupC);
mCallback.onGroupMCheckListener(groupC, isChecked, nFragment);
}
}
};
}
PS. I use the nf in another project