I need to help. I tried to back to previous activity, but when I click arrow button (action bar) it show errors. Can someone help me .. please!
Thank's before for your answers
This is my codes:
First, I get data in KitabActivity (so this is the first activity):
KitabActivity:
public class KitabActivity extends AppCompatActivity {
private List<Kitab> kitabList;
private RecyclerView recyclerView;
private KitabAdapter kitabAdapter;
private RecyclerView.LayoutManager layoutManager;
private Toolbar toolbar;
private ActionBar actionBar;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_kitab);
toolbar = (Toolbar) findViewById(R.id.toolbar);
toolbar.setTitle("Kitab Hadits");
setSupportActionBar(toolbar);
actionBar = getSupportActionBar();
actionBar.setDisplayHomeAsUpEnabled(true);
recyclerView = (RecyclerView) findViewById(R.id.rv_main_kitab);
recyclerView.setHasFixedSize(true);
layoutManager = new LinearLayoutManager(this);
recyclerView.setLayoutManager(layoutManager);
kitabList = new ArrayList<>();
getDataKitab();
}
private void getDataKitab() {
final ProgressDialog loading = ProgressDialog.show(this,"Mohon Tunggu...","Sedang mengambil data...",false,false);
JsonArrayRequest jsonArrayRequest = new JsonArrayRequest(ConfigKitab.DATA_URL_KITAB, new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray jsonArray) {
loading.dismiss();
parseData(jsonArray);
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError volleyError) {
loading.dismiss();
Toast.makeText(KitabActivity.this, "Gagal koneksi ke server!", Toast.LENGTH_SHORT).show();
}
});
RequestQueue requestQueue = Volley.newRequestQueue(this);
requestQueue.add(jsonArrayRequest);
}
private void parseData(JSONArray jsonArray) {
for(int i=0;i<jsonArray.length();i++){
Kitab kitab = new Kitab();
JSONObject jsonObject = null;
try{
jsonObject = jsonArray.getJSONObject(i);
kitab.setId_kitab(jsonObject.getString(ConfigKitab.TAG_ID_KITAB));
kitab.setNama_kitab(jsonObject.getString(ConfigKitab.TAG_NAMA_KITAB));
}catch(JSONException e){
e.printStackTrace();
}
kitabList.add(kitab);
}
kitabAdapter = new KitabAdapter(kitabList,this);
recyclerView.setAdapter(kitabAdapter);
}
}
In KitabAdapter, I pass KEY_ID to BabKitabActivity:
This is KitabAdapter:
public class KitabAdapter extends RecyclerView.Adapter<KitabVH> {
private Context context;
List<Kitab> kitabList;
public KitabAdapter(List<Kitab> kitabList, Context context){
super();
this.kitabList = kitabList;
this.context = context;
}
#Override
public KitabVH onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.list_kitab,parent,false);
return new KitabVH(view);
}
#Override
public void onBindViewHolder(KitabVH holder, int position) {
final Kitab kitab = kitabList.get(position);
holder.bind(kitab);
holder.cv_kitab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(v.getContext(), BabKitabActivity.class);
intent.putExtra("KEY_ID",kitab.getId_kitab());
intent.putExtra("KEY_NAMA",kitab.getNama_kitab());
v.getContext().startActivity(intent);
}
});
}
#Override
public int getItemCount() {
return kitabList.size();
}
}
BabKitabActivity:
public class BabKitabActivity extends AppCompatActivity {
private List<BabKitab> babKitabList;
private RecyclerView recyclerView;
private BabKitabAdapter babKitabAdapter;
private RecyclerView.LayoutManager layoutManager;
private Toolbar toolbarBab;
private ActionBar actionBar;
private String id_kitab;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_bab_kitab);
toolbarBab = (Toolbar) findViewById(R.id.toolbarBab);
toolbarBab.setTitle(getIntent().getExtras().getString("KEY_NAMA"));
setSupportActionBar(toolbarBab);
actionBar = getSupportActionBar();
actionBar.setDisplayHomeAsUpEnabled(true);
recyclerView = (RecyclerView) findViewById(R.id.rv_main_bab);
recyclerView.setHasFixedSize(true);
layoutManager = new LinearLayoutManager(this);
recyclerView.setLayoutManager(layoutManager);
babKitabList = new ArrayList<>();
getDataBab();
}
private void getDataBab() {
id_kitab = getIntent().getExtras().getString("KEY_ID");
String url = ConfigBabKitab.DATA_URL_BAB+id_kitab;
final ProgressDialog loading = ProgressDialog.show(this,"Mohon Tunggu...","Sedang mengambil data...",false,false);
JsonArrayRequest jsonArrayRequest = new JsonArrayRequest(url, new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray jsonArray) {
loading.dismiss();
parseData(jsonArray);
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError volleyError) {
loading.dismiss();
Toast.makeText(BabKitabActivity.this, "Gagal Koneksi ke Server!", Toast.LENGTH_SHORT).show();
}
});
RequestQueue requestQueue = Volley.newRequestQueue(this);
requestQueue.add(jsonArrayRequest);
}
private void parseData(JSONArray response) {
for(int i=0;i<response.length();i++){
BabKitab babKitab = new BabKitab();
JSONObject obj = null;
try{
obj = response.getJSONObject(i);
babKitab.setId_bab_kitab(obj.getString(ConfigBabKitab.TAG_ID_BAB));
babKitab.setNomor_bab(obj.getString(ConfigBabKitab.TAG_NOMOR_BAB));
babKitab.setNama_bab(obj.getString(ConfigBabKitab.TAG_NAMA_BAB));
babKitab.setPenjelasan(obj.getString(ConfigBabKitab.TAG_PENJELASAN));
}catch(JSONException e){
e.printStackTrace();
}
babKitabList.add(babKitab);
}
babKitabAdapter = new BabKitabAdapter(babKitabList,this);
recyclerView.setAdapter(babKitabAdapter);
}
}
DetailActivity:
public class DetailActivity extends AppCompatActivity {
private RecyclerView recyclerView;
private List<DetailHadits> detailHaditsList;
private DetailAdapter detailAdapter;
private String id_bab_kitab;
private TextView tv_penjelasan;
private String penjelasan;
private CardView cv;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_detail);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbarDetail);
setSupportActionBar(toolbar);
ActionBar actionBar = getSupportActionBar();
actionBar.setDisplayHomeAsUpEnabled(true);
cv = (CardView) findViewById(R.id.cv);
tv_penjelasan = (TextView) findViewById(R.id.tv_penjelasan);
//cv.setVisibility(View.GONE);
//tv_penjelasan.setVisibility(View.GONE);
penjelasan = getIntent().getExtras().getString("KEY_PENJELASAN");
tv_penjelasan.setText(penjelasan);
recyclerView = (RecyclerView) findViewById(R.id.rv_main_detail);
//recyclerView.setHasFixedSize(true);
LinearLayoutManager layoutManager = new LinearLayoutManager(this);
recyclerView.setLayoutManager(layoutManager);
detailHaditsList = new ArrayList<>();
getAyat();
}
private void getAyat() {
id_bab_kitab = getIntent().getExtras().getString("KEY_ID");
String url = ConfigDetail.DATA_URL_AYAT+id_bab_kitab;
final ProgressDialog loading = ProgressDialog.show(this,"Mohon Tunggu...","Sedang mengambil data...",false,false);
JsonArrayRequest jsonArrayRequest = new JsonArrayRequest(url, new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray jsonArray) {
loading.dismiss();
parseData(jsonArray);
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError volleyError) {
loading.dismiss();
Toast.makeText(DetailActivity.this, "Error", Toast.LENGTH_SHORT).show();
}
});
RequestQueue requestQueue = Volley.newRequestQueue(this);
requestQueue.add(jsonArrayRequest);
}
private void parseData(JSONArray jsonArray) {
for(int i=0;i<jsonArray.length();i++){
DetailHadits detailHadits = new DetailHadits();
JSONObject obj = null;
try{
obj = jsonArray.getJSONObject(i);
detailHadits.setUrlGambarAyat(obj.getString(ConfigDetail.TAG_GAMBAR));
detailHadits.setTerjemahanAyat(obj.getString(ConfigDetail.TAG_TERJEMAHAN));
}catch(JSONException e){
e.printStackTrace();
}
detailHaditsList.add(detailHadits);
}
detailAdapter = new DetailAdapter(detailHaditsList,this);
recyclerView.setAdapter(detailAdapter);
}
}
and this is the log cat:
FATAL EXCEPTION: main
Process: id.hadits.pencarian.skripsi.nana.aplikasipencarianhadits, PID: 15228
java.lang.RuntimeException: Unable to start activity ComponentInfo{id.hadits.pencarian.skripsi.nana.aplikasipencarianhadits/id.hadits.pencarian.skripsi.nana.aplikasipencarianhadits.Activity.BabKitabActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String android.os.Bundle.getString(java.lang.String)' on a null object reference
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2298)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2360)
at android.app.ActivityThread.access$800(ActivityThread.java:144)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1278)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5221)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:899)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:694)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String android.os.Bundle.getString(java.lang.String)' on a null object reference
at id.hadits.pencarian.skripsi.nana.aplikasipencarianhadits.Activity.BabKitabActivity.onCreate(BabKitabActivity.java:46)
at android.app.Activity.performCreate(Activity.java:5933)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1105)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2251)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2360)
at android.app.ActivityThread.access$800(ActivityThread.java:144)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1278)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5221)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
thank's in advance ;)
So, in my case BabKitabActivity can load data if there is a KEY_ID from KitabActivity (i guess).
What I want is just go back to previous activity (in this case to BabKitabActivity) without getting KEY_ID again.
It work with button back in emulator or smartphone, but it doesn't work with arrow button in actionbar, what should I do?
before getIntent().getExtras() check its null or not
Bundle extras = getIntent().getExtras();
if (extras != null) {
penjelasan = extras.getString("KEY_PENJELASAN");
}
something like
if (extras != null) {
id_bab_kitab = extras.getString("KEY_ID");
}
Unable to start activity ComponentInfo{id.hadits.pencarian.skripsi.nana.aplikasipencarianhadits/id.hadits.pencarian.skripsi.nana.aplikasipencarianhadits.Activity.BabKitabActivity}:
java.lang.NullPointerException: Attempt to invoke virtual method
'java.lang.String android.os.Bundle.getString(java.lang.String)' on a
null object reference
Issue is in your BatkitabActivity. You are getting string from intent which is null. Before getting string value, you can check if intent is null or not.
Bundle extras = getIntent().getExtras();
if (extras != null) {
....
}
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String android.os.Bundle.getString(java.lang.String)' on a null object reference
at id.hadits.pencarian.skripsi.nana.aplikasipencarianhadits.Activity.BabKitabActivity.onCreate(BabKitabActivity.java:46)
penjelasan = getIntent().getExtras().getString("KEY_PENJELASAN");
you can get the Bundle's data from getIntent().getExtras(), but you get null, so you got the NullPointerException, that make a crash in your app.
Related
My RecycleView is in my Activity and then I want to set it in my other class. But it always say NullObjectReference with my RecycleView. I dont know why because i have initialize it. Is there something wrong? Here is my code
My Activity
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
RecyclerView recyclerView;
VolleyGet volleyGet;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initRecycle();
volleyGet = new VolleyGet();
RecyclerView.LayoutManager mLayoutManager = new LinearLayoutManager(getApplicationContext());
recyclerView.setLayoutManager(mLayoutManager);
Button get = (Button) findViewById(R.id.get);
get.setOnClickListener(this);
}
public void initRecycle(){
recyclerView = findViewById(R.id.recycleview);
}
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.get:
volleyGet.volleyRequest(this);
break;
default:
break;
}
}
My Other Class (RecycleView must be set here)
public class VolleyGet {
RecyclerView recyclerView;
public RecycleAdapter adapter;
public ArrayList<User> listUser;
public void volleyRequest(final Context context) {
MainActivity mainActivity = new MainActivity();
mainActivity.initRecycle();
listUser = new ArrayList<>();
adapter = new RecycleAdapter(context, listUser);
String URL = "http://192.168.180.7:8080/get.php";
RequestQueue queue = Volley.newRequestQueue(context);
StringRequest stringRequest = new StringRequest(Request.Method.GET, URL,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONArray array = new JSONArray(response);
for (int i = 0; i < array.length(); i++) {
ArrayList<User> items = new Gson().fromJson(response.toString(), new TypeToken<ArrayList<User>>() {
}.getType());
listUser.clear();
listUser.addAll(items);
}
recyclerView.setAdapter(adapter);
} catch (JSONException e) { e.printStackTrace(); } }},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) { }}) {};
queue.add(stringRequest);
}
Looks like the RecycleView init with calling a method. You can try initialize with other way like using Activity like this.
Activity activity;
and this how to get your activity
public VolleyGet(Activity _activity){
this.activity = _activity;
recyclerView = (RecyclerView) this.activity.findViewById(R.id.recycleview);
}
or you can do this if you want to use Context
public VolleyGet(Context context){
recyclerView = (RecyclerView) ((Activity)context).findViewById(R.id.recycleview);
}
dont forget to add this in your MainActivity for sending your activity
volleyGet = new VolleyGet(this);
so the whole code of your other class must be like this
public class VolleyGet {
RecyclerView recyclerView;
public RecycleAdapter adapter;
public ArrayList<User> listUser;
Activity activity;
public VolleyGet(Activity _activity){
this.activity = _activity;
recyclerView = (RecyclerView) this.activity.findViewById(R.id.recycleview);
}
public void volleyRequest(final Context context) {
listUser = new ArrayList<>();
adapter = new RecycleAdapter(context, listUser);
String URL = "http://192.168.180.7:8080/get.php";
RequestQueue queue = Volley.newRequestQueue(context);
StringRequest stringRequest = new StringRequest(Request.Method.GET, URL,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONArray array = new JSONArray(response);
for (int i = 0; i < array.length(); i++) {
ArrayList<User> items = new Gson().fromJson(response.toString(), new TypeToken<ArrayList<User>>() {
}.getType());
listUser.clear();
listUser.addAll(items);
}
recyclerView.setAdapter(adapter);
} catch (JSONException e) { e.printStackTrace(); } }},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) { }}) {};
queue.add(stringRequest);
Hello guys iam trying to get Data to putExtra => Intent from an Adapter to another Activity but every time i try to get data from the Adapter to the Activity it Gives me this Exception that
java.lang.String android.content.Context.getPackageName()'
so i tried to Enter the Context class i found it too many Errors cant fix that till now
what makes me really Believe that the problem with the Context is that when i Tried to use TinyDB
it need to define the Object inside the Adapter
tinyDB = new TinyDB(mContext);
the program Crashed and Gives Me this Exception
W/System.err: java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String android.content.Context.getPackageName()' on a null object reference
W/System.err: at android.content.ComponentName.<init>(ComponentName.java:128)
at android.content.Intent.<init>(Intent.java:4910)
at com.team.plustegara.Views.Models.Adapters.EventsAdapter$1.onClick(EventsAdapter.java:83)
at android.view.View.performClick(View.java:5647)
at android.view.View$PerformClick.run(View.java:22465)
at android.os.Handler.handleCallback(Handler.java:754)
at android.os.Handler.dispatchMessage(Handler.java:95)
W/System.err: at android.os.Looper.loop(Looper.java:163)
at android.app.ActivityThread.main(ActivityThread.java:6238)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:904)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:794)
i tried to Fix that but still cant handle the Context problem
Here is my Adapter
public class EventsAdapter extends RecyclerView.Adapter<EventsAdapter.EventsHolder> {
public EventsAdapter(List<EventsModel> list, Context mContext) {
this.list = list;
this.mContext = mContext;
}
private List<EventsModel> list;
private Context mContext;
FirebaseAuth mAuth;
DatabaseReference dbRef;
#NonNull
#Override
public EventsHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.events_row_item, parent, false);
EventsHolder holder = new EventsHolder(view);
return holder;
}
#Override
public void onBindViewHolder(#NonNull final EventsHolder holder, int position) {
final EventsModel listy = list.get(position);
holder.eventTitle.setText(listy.getTitle());
holder.eventDate.setText(listy.getEventDate());
holder.eventCosts.setText("Event Costs " + listy.getCosts());
Picasso.get()
.load(listy.getEventImage())
.fit()
.centerCrop()
.placeholder(R.drawable.gradients_card)
.into(holder.eventImage);
holder.cardViewEvents.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
try {
Intent intent = new Intent(mContext, ShowActivityEvents.class);
intent.putExtra("EventImage", listy.getEventImage());
intent.putExtra("EventTitle", listy.getTitle());
intent.putExtra("EventDate", listy.getEventDate());
intent.putExtra("EventCosts", listy.getCosts());
intent.putExtra("EventDescription", listy.getDescription());
intent.putExtra("eventID", listy.getPostID());
mContext.startActivity(intent);
dbRef = FirebaseDatabase.getInstance().getReference("PlusTeam");
mAuth = FirebaseAuth.getInstance();
String userName = mAuth.getCurrentUser().getDisplayName();
String postID = listy.getPostID();
dbRef.child("Events").child(postID).child("Views").push().setValue(userName);
} catch (Exception e) {
e.printStackTrace();
}
}
});
String postID = listy.getPostID();
DatabaseReference databaseReference = FirebaseDatabase.getInstance().getReference("PlusTeam");
databaseReference.child("Events").child(postID).child("Views").addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
long ViewsCount = dataSnapshot.getChildrenCount();
holder.txtViews.setText(String.valueOf(ViewsCount));
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
Toasty.error(mContext, databaseError.getMessage(), Toast.LENGTH_LONG).show();
}
});
}
#Override
public int getItemCount() {
return list.size();
}
public class EventsHolder extends RecyclerView.ViewHolder {
#BindView(R.id.EventImageCard)
ImageView eventImage;
#BindView(R.id.txtEventTitle)
TextView eventTitle;
#BindView(R.id.txtEventDate)
TextView eventDate;
#BindView(R.id.txtEventCosts)
TextView eventCosts;
#BindView(R.id.cardView_EventsCard)
CardView cardViewEvents;
#BindView(R.id.txtEventsViews) TextView txtViews;
public EventsHolder(View itemView) {
super(itemView);
ButterKnife.bind(this, itemView);
}
}
}
here is my Activity which receive the Extras from the Adapter
public class ShowActivityEvents extends AppCompatActivity {
DatabaseReference dbRef;
FirebaseAuth mAuth;
#Override
protected void onStart() {
super.onStart();
checkIfUserAlreadyAccepttheEvent();
}
private void checkIfUserAlreadyAccepttheEvent() {
final String postID = getIntent().getExtras().getString("eventID");
final String UserID = mAuth.getCurrentUser().getUid();
dbRef.child(postID).child("PeopleComing")
.addListenerForSingleValueEvent(new ValueEventListener() {
public static final String TAG = "ShowEvents";
#SuppressLint("SetTextI18n")
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
Log.e(TAG, "onChildAdded: " + dataSnapshot);
String peopleCount = String.valueOf(dataSnapshot.getChildrenCount());
txtPeopleComing.setText( peopleCount + " People Comming");
if (dataSnapshot.child(UserID).exists()) {
btnIamIn.setEnabled(false);
} else {
btnIamIn.setEnabled(true);
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
Toasty.error(ShowActivityEvents.this, "Error code : " + 1, Toast.LENGTH_LONG).show();
}
});
}
#BindView(R.id.btnIamIn)
Button btnIamIn;
#BindView(R.id.txtPeopleComingCount)
TextView txtPeopleComing;
#BindView(R.id.imgEventPost)
ImageView imgEvent;
#BindView(R.id.txtEventTitle) TextView txtEventTitle;
#BindView(R.id.txtEventDescription) TextView txtEventDescription;
#BindView(R.id.txtEventCost) TextView txtEventCost;
#BindView(R.id.txtEventDate) TextView txtEventDate;
Intent intent;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_show_events2);
ButterKnife.bind(this);
dbRef = FirebaseDatabase.getInstance().getReference("PlusTeam");
mAuth = FirebaseAuth.getInstance();
try {
loadDataFromAdapter();
} catch (Exception e) {
e.printStackTrace();
}
}
private void loadDataFromAdapter() {
String Image = getIntent().getExtras().getString("EventImage");
String Title = getIntent().getExtras().getString("EventTitle");
String Date = getIntent().getExtras().getString("EventDate");
String Costs = getIntent().getExtras().getString("EventCosts");
String Description = getIntent().getExtras().getString("EventDescription");
GlideApp.with(this)
.load(Image)
.fitCenter()
.into(imgEvent);
txtEventTitle.setText(Title);
txtEventDescription.setText(Description);
txtEventDate.setText(Date);
txtEventCost.setText(Costs);
}
#OnClick(R.id.btnIamIn) public void addPersonToEvent(){
String UserName = mAuth.getCurrentUser().getDisplayName();
String userID = mAuth.getCurrentUser().getUid();
String postID = getIntent().getExtras().getString("eventID");
dbRef.child(postID)
.child("PeopleComing").setValue(UserName);
btnIamIn.setEnabled(false);
}
}
Finally just wanted to say i searched for this kind of Problem in Google and inside questions in Stack but didn't worked
so any Suggestions
You should pass your context in adapter like in the example below
Activity
adapter = new EventsAdapter(myList,MainActivity.this);
Fragment
adapter = new EventsAdapter(myList,getActivity());
Or another way
#Override
public void onClick(View v) {
v.getContext().startActivity(v.getContext(), ShowActivityEvents.class);
}
I am trying to load some items from JSON, I am able to get and parse the JSON and load it up in listview when using one activity. However, I want to use a LoadJSON.class to load the JSON, and then the activity can call the json passed and show it in the listview in that activity.
Here is what I have tried:
SongsManager.class
public class SongsManager {
private String TAG = SongsManager.class.getSimpleName();
private static final String API_URL = "http://xxxxxxxxxxxxx.com/jame/mp3/songlist.json";
private List<SolTracks> solTracksList;
private ProgressDialog pDialog;
private final Activity activity;
public SongsManager(Activity activity) {
this.activity = activity;
solTracksList = new ArrayList<>();
pDialog = new ProgressDialog(activity);
fetchSongs();
}
private void fetchSongs() {
pDialog.setMessage("Fetching Playlist...");
pDialog.show();
// Volley's json array request object
JsonArrayRequest req = new JsonArrayRequest(API_URL,
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
Log.d(TAG, "Responser = " + response.toString());
pDialog.hide();
if (response.length() > 0) {
// looping through json and adding to movies list
for (int i = 0; i < response.length(); i++) {
try {
JSONObject movieObj = response.getJSONObject(i);
String songTitle = movieObj.getString("title");
String songId = movieObj.getString("id");
String streamUrl = movieObj.getString("stream_url");
SolTracks m = new SolTracks(songTitle, songId, streamUrl);
solTracksList.add(m);
Collections.sort(solTracksList, new TrackComparator());
} catch (JSONException e) {
Log.e(TAG, "JSON Parsing error: " + e.getMessage());
}
}
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e(TAG, "Server Error: " + error.getMessage());
pDialog.hide();
Snackbar snackbar = Snackbar
.make(activity.findViewById(android.R.id.content), "PLEASE CHECK YOUR INTERNET", Snackbar.LENGTH_LONG)
.setAction("DISMISS", new View.OnClickListener() {
#Override
public void onClick(View view) {
}
});
// Changing snackbar background
snackbar.getView().setBackgroundColor(ContextCompat.getColor(activity, R.color.colorPrimary));
// Changing message text color
snackbar.setActionTextColor(Color.YELLOW);
// Changing action button text color
View sbView = snackbar.getView();
TextView textView = (TextView) sbView.findViewById(android.support.design.R.id.snackbar_text);
textView.setTextColor(Color.WHITE);
snackbar.show();
}
});
req.setRetryPolicy(new DefaultRetryPolicy(0, DefaultRetryPolicy.DEFAULT_MAX_RETRIES, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
// Adding request to request queue
AppController.getInstance().addToRequestQueue(req);
}
public List<SolTracks> getList() {
return solTracksList;
}
Activity class
public class TheMain1 extends AppCompatActivity {
private SwipeRefreshLayout swipeRefreshLayout;
private String TAG = TheMain1.class.getSimpleName();
private static final String API_URL = "http://xxxxxxxxxxx.com/jame/mp3/songlist.json";
private ListView listView;
private SolTracksAdapter adapter;
private ProgressDialog pDialog;
private List<SolTracks> songslist;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_the_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
listView = (ListView) findViewById(R.id.track_list_view);
songslist = new ArrayList<>();
SongsManager songsManager = new SongsManager(this);
songslist = songsManager.getList();
adapter = new SolTracksAdapter(this, songslist);
listView.setAdapter(adapter);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener()
{
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
SolTracks track = songslist.get(position);
final String stream_url = track.stream_url;
final String id_url = track.id;
Intent intent = new Intent(TheMain1.this, PlayerActivity.class);
intent.putExtra("songPosition", position);
intent.putExtra("streamUrl", stream_url);
startActivity(intent);
}
}
);
}
As it is right now, I know the JSON is loaded from SongsManager, but its just not displaying in the listview of the Activity class. Can anyone help, and show what I'm doing wrong? Thanks
I was able to fix this by implementing Parcelable to send the list to the receiving activity.
public class SolTracks implements Parcelable {
public String title;
public String id;
public String stream_url;
}
Sending the list from the Activity A:
Intent intent = new Intent(TheMain.this, PlayerActivity.class);
Bundle bundle = new Bundle();
bundle.putParcelableArrayList("mylist", solTracksList);
intent.putExtras(bundle);
intent.putExtra("songPosition", position);
startActivity(intent);
and then receiving in Activity B:
Bundle extras = getIntent().getExtras();
if (extras != null) {
songPosition = extras.getInt("songPosition");
trackList = extras.getParcelableArrayList("mylist");
}
I got an error with notifyDataSetChanged() on RecyclerView when I press back button. This is the code:
MainActivity.java
class MainActivity extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener {
public List<Article> articleList;
public RecyclerView recyclerView;
public RecyclerViewAdapter adapter;
ArrayList<String> my_list = new ArrayList<String>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
LinearLayoutManager layoutManager = new LinearLayoutManager(this);
recyclerView = (RecyclerView) findViewById(R.id.recyclerView);
initData();
adapter = new RecyclerViewAdapter(articleList, MainActivity.this);
recyclerView.setAdapter(adapter);
}
private void initData() {
articleList = new ArrayList<>();
queryArticle();
}
public void saveArticle(String title, String desc) {
//ab is a instance for class Article_Bmob
ab.setTitle(title);
ab.setDesc(desc);
ab.save(new SaveListener<String>() {
#Override
public void done(String s, BmobException e) {
if(e == null) {
} else {
e.printStackTrace();
}
}
});
}
}
WriteArticle.java (Error File)
public class WriteArticle extends AppCompatActivity {
MainActivity mainActivity;
private String art_title, art_desc;
private EditText edt_title, edt_desc;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.write_article);
edt_title = (EditText) findViewById(R.id.w_art_title);
edt_desc = (EditText) findViewById(R.id.w_art_desc);
Button btn_send = (Button) findViewById(R.id.send_article);
mainActivity = new MainActivity();
btn_send.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
art_title = edt_title.getText().toString();
art_desc = edt_desc.getText().toString();
if (art_title.isEmpty()) {
Snackbar.make(view, "R.String.xxx", Snackbar.LENGTH_LONG)
.setAction("Action", null).show();
} else if (art_desc.isEmpty()) {
Snackbar.make(view, "R.String.xxx", Snackbar.LENGTH_LONG)
.setAction("Action", null).show();
} else {
mainActivity.saveArticle(art_title, art_desc);
mainActivity.adapter.notifyDataSetChanged();
finish();
}
}
});
}
And the error:
java.lang.NullPointerException: Attempt to invoke virtual method
'void com.myapplication.RecyclerViewAdapter.notifyDataSetChanged()' on a null object reference
at com.myapplication.WriteArticle$1.onClick(WriteArticle.java:52)
How can I solve this?
In your MainActivity
public static MainActivity mactivity;
public static MainActivity getinstance(){
return mactivity;
}
In your WriteArticle activity
MainActivity mainActivity;
And use it as
mainActivity.getinstance.saveArticle(art_title, art_desc);
mainActivity.getinstance.adapter.notifyDataSetChanged();
This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 6 years ago.
I have an app in which when an activity is started shows nullpointer exception, but I can't understand what the error is and where I'm doing wrong. I'm new to android and I would be grateful if you could help. Thanks in advance.`
This is the activity which shows the error when started AccountsActivity.java
public class AccountsActivity extends AppCompatActivity {
SharedPreferences myPrefs = PreferenceManager.getDefaultSharedPreferences(OpeningScreenActivity.getContextOfApplication());
String token = myPrefs.getString("GCMTOKEN", "");
String JSON_URL = "http://xyz.in/view_json.php?device_id=" + token;
private ListView listView;
/**
* ATTENTION: This was auto-generated to implement the App Indexing API.
* See https://g.co/AppIndexing/AndroidStudio for more information.
*/
private GoogleApiClient client;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_accounts);
listView = (ListView) findViewById(R.id.listView);
sendRequest();
// ATTENTION: This was auto-generated to implement the App Indexing API.
// See https://g.co/AppIndexing/AndroidStudio for more information.
client = new GoogleApiClient.Builder(this).addApi(AppIndex.API).build();
}
private void sendRequest() {
StringRequest stringRequest = new StringRequest(JSON_URL,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
showJSON(response);
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(AccountsActivity.this, error.getMessage(), Toast.LENGTH_LONG).show();
}
});
RequestQueue requestQueue = Volley.newRequestQueue(this);
requestQueue.add(stringRequest);
}
private void showJSON(String json) {
ParseJSON pj = new ParseJSON(json);
pj.parseJSON();
CustomList cl = new CustomList(this, ParseJSON.ids,ParseJSON.mem_codes,ParseJSON.created_ons);
listView.setAdapter(cl);
}
}
This is ParseJSON.java class
public class AccountsActivity extends AppCompatActivity {
SharedPreferences myPrefs = PreferenceManager.getDefaultSharedPreferences(OpeningScreenActivity.getContextOfApplication());
String token = myPrefs.getString("GCMTOKEN", "");
String JSON_URL = "http://sovran.in/sov2fa_v2/view_json.php?device_id=" + token;
private ListView listView;
/**
* ATTENTION: This was auto-generated to implement the App Indexing API.
* See https://g.co/AppIndexing/AndroidStudio for more information.
*/
private GoogleApiClient client;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_accounts);
listView = (ListView) findViewById(R.id.listView);
sendRequest();
// ATTENTION: This was auto-generated to implement the App Indexing API.
// See https://g.co/AppIndexing/AndroidStudio for more information.
client = new GoogleApiClient.Builder(this).addApi(AppIndex.API).build();
}
private void sendRequest() {
StringRequest stringRequest = new StringRequest(JSON_URL,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
showJSON(response);
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(AccountsActivity.this, error.getMessage(), Toast.LENGTH_LONG).show();
}
});
RequestQueue requestQueue = Volley.newRequestQueue(this);
requestQueue.add(stringRequest);
}
private void showJSON(String json) {
ParseJSON pj = new ParseJSON(json);
pj.parseJSON();
CustomList cl = new CustomList(this, ParseJSON.ids,ParseJSON.mem_codes,ParseJSON.created_ons);
listView.setAdapter(cl);
}
}
This is CustomList.java
public class CustomList extends ArrayAdapter<String> {
private String[] ids;
private String[] mem_codes;
private String[] created_ons;
private Activity context;
public CustomList(Activity context, String[] ids, String[] mem_codes, String[] created_ons) {
super(context, R.layout.list_view_layout, ids);
this.context = context;
this.ids = ids;
this.mem_codes = mem_codes;
this.created_ons = created_ons;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
LayoutInflater inflater = context.getLayoutInflater();
View listViewItem = inflater.inflate(R.layout.list_view_layout, null, true);
TextView textViewId = (TextView) listViewItem.findViewById(R.id.textViewId);
TextView textViewMemCode = (TextView) listViewItem.findViewById(R.id.textViewMem_code);
TextView textViewCreatedOn = (TextView) listViewItem.findViewById(R.id.textViewCreated_on);
textViewId.setText(ids[position]);
textViewMemCode.setText(mem_codes[position]);
textViewCreatedOn.setText(created_ons[position]);
return listViewItem;
}
}
And this is the error log
07-15 14:04:46.269 32255-32255/com.sovran.sov2fa E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.sovran.sov2fa, PID: 32255
java.lang.ExceptionInInitializerError
at java.lang.reflect.Constructor.newInstance(Native Method)
at java.lang.Class.newInstance(Class.java:1606)
at android.app.Instrumentation.newActivity(Instrumentation.java:1071)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2416)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2614)
at android.app.ActivityThread.access$800(ActivityThread.java:178)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1470)
at android.os.Handler.dispatchMessage(Handler.java:111)
at android.os.Looper.loop(Looper.java:194)
at android.app.ActivityThread.main(ActivityThread.java:5653)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:960)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:755)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String android.content.Context.getPackageName()' on a null object reference
at android.preference.PreferenceManager.getDefaultSharedPreferencesName(PreferenceManager.java:383)
at android.preference.PreferenceManager.getDefaultSharedPreferences(PreferenceManager.java:378)
at com.sovran.sov2fa.AccountsActivity.<clinit>(AccountsActivity.java:20)
at java.lang.reflect.Constructor.newInstance(Native Method)
at java.lang.Class.newInstance(Class.java:1606)
at android.app.Instrumentation.newActivity(Instrumentation.java:1071)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2416)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2614)
at android.app.ActivityThread.access$800(ActivityThread.java:178)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1470)
at android.os.Handler.dispatchMessage(Handler.java:111)
at android.os.Looper.loop(Looper.java:194)
at android.app.ActivityThread.main(ActivityThread.java:5653)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:960)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:755)
Do the initialization of your myPrefs attribute within onCreate()-method
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_accounts);
myPrefs = PreferenceManager.getDefaultSharedPreferences(this);
...
}