Confused with NullPointerException - nullpointerexception

I know that i am probably missing something simple but i am getting this error when i try to load my second activity and i have no idea why, I understand (Or iv'e been told) That it happens when your code doesn't point to anything, But iv'e checked it and it points to the correct location.
ResultText
package com.example.mdpmk1;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
public class ResultText extends Activity {
Button button;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
addListenerOnButton();
//Points /\
}
public void addListenerOnButton() {
final Context context = this;
button = (Button) findViewById(R.id.returnHome);
button.setOnClickListener(new OnClickListener() {
//Points /\
#Override
public void onClick(View arg0) {
Intent intent = new Intent(context, MainActivity.class);
startActivity(intent);
}
});
String result=getIntent().getStringExtra("resultText");
setContentView(R.layout.result_text);
TextView tv=new TextView(this);
tv.setTextSize(20);
String str=result;
tv.setText(str);
setContentView(tv);
}
}
If you require any more of the files feel free to ask.
Sorry if its a noob question and thanks for the help in advance.

call setContentView(R.layout.result_text); before calling addListenerOnButton();
Like:
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.result_text);
addListenerOnButton();
}

Related

I have got this error (Attempt to invoke virtual method 'void android.widget.TextView.setText(java.lang.CharSequence)' on a null object reference)

I am trying to display the API data in the recyclerView but facing
this error In the viewHolder.I'm trying to set the text of the textviews from the fetched data on my API, but when i try to do so, it
throws the following error (Attempt to invoke virtual method 'void
android.widget.TextView.setText(java.lang.CharSequence)' on a null
object reference)
package com.example.restfulapi;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;
import com.squareup.picasso.Picasso;
import java.util.ArrayList;
import java.util.List;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
public class DataViewActivity extends AppCompatActivity {
RecyclerView recyclerView;
private static final String TAG = "DataViewActivity";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.data_view);
recyclerView = findViewById(R.id.recycle);
listingData();
LinearLayoutManager llm = new LinearLayoutManager(getApplicationContext(),LinearLayoutManager.VERTICAL, false );
recyclerView.setLayoutManager(llm);
}
private void listingData() {
Methods methods = RetrofitClient.getRetrofitInstance().create(Methods.class);
Call<Model> listingData = methods.getAllData();
listingData.enqueue(new Callback<Model>() {
#Override
public void onResponse(Call<Model> call, Response<Model> response) {
if (response.isSuccessful()) {
recycleAdapter adapter =new recycleAdapter(response.body().getData());
recyclerView.setAdapter(adapter);
}
}
#Override
public void onFailure(Call<Model> call, Throwable t) {
Toast.makeText(DataViewActivity.this, "Failure", Toast.LENGTH_SHORT).show();
}
});
}
class recycleAdapter extends RecyclerView.Adapter<recycleAdapter.MyViewHolder>
{
List<Model.data> list;
public recycleAdapter(List<Model.data> list) {
this.list = list;
}
#NonNull
#Override
public recycleAdapter.MyViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.users,null);
recycleAdapter.MyViewHolder viewHolder = new recycleAdapter.MyViewHolder(view);
return viewHolder;
}
#Override
public void onBindViewHolder(#NonNull recycleAdapter.MyViewHolder holder, int position) {
holder.userEmail.setText(list.get(position).getEmail());
holder.firstName.setText(list.get(position).getFirst_name());
holder.lastName.setText(list.get(position).getLast_name());
Picasso.with(getApplicationContext()).load(list.get(position).getAvatar())
.placeholder(R.drawable.ic_launcher_background).fit().into(holder.userImage);
}
#Override
public int getItemCount() {
return list.size();
}
class MyViewHolder extends RecyclerView.ViewHolder{
TextView firstName,lastName,userEmail;
ImageView userImage;
There is an error on this section below, I have mentioned the error
above.Am I missing something or did I do something wrong in my code?
public MyViewHolder(#NonNull View itemView) {
super(itemView);
firstName =(TextView) findViewById(R.id.firstName);
lastName = (TextView) findViewById(R.id.lastName);
userEmail = (TextView) findViewById(R.id.userEmail);
userImage = (ImageView) findViewById(R.id.userImage);
}
}
}
}

RecyclerView and Item Position and click on particular item

This is the interface of my application, my question is, if I click on "video lecture" then it should go to Video Lecture Activity and if i click on "Detail Notes" then it should go in Detail Notes Activity. Similarly, i want to do with all recyclerView items.
This is my Adapter code
package com.example.motionofknowledge;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.GridLayoutManager;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import com.example.motionofknowledge.databinding.ActivityMaterialsBinding;
import com.google.firebase.firestore.DocumentSnapshot;
import com.google.firebase.firestore.EventListener;
import com.google.firebase.firestore.FirebaseFirestore;
import com.google.firebase.firestore.FirebaseFirestoreException;
import com.google.firebase.firestore.QuerySnapshot;
import java.util.ArrayList;
public class Materials extends AppCompatActivity {
ActivityMaterialsBinding binding;
FirebaseFirestore database;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
binding = ActivityMaterialsBinding.inflate(getLayoutInflater());
setContentView(binding.getRoot());
getSupportActionBar().hide();
String head = getIntent().getStringExtra("subName");
TextView textView = findViewById(R.id.headingMat);
textView.setText(new String(head));
database = FirebaseFirestore.getInstance();
ArrayList<MatModel> materials = new ArrayList<>();
MatAdapter adapter = new MatAdapter(this,materials);
String subId = getIntent().getStringExtra("subId");
database.collection("subjects")
.document(subId)
.collection("mat")
.orderBy("index")
.addSnapshotListener(new EventListener<QuerySnapshot>() {
#Override
public void onEvent(#Nullable QuerySnapshot value, #Nullable FirebaseFirestoreException error) {
materials.clear();
for (DocumentSnapshot snapshot:value.getDocuments()){
MatModel model = snapshot.toObject(MatModel.class);
model.setMatId(snapshot.getId());
materials.add(model);
}
adapter.notifyDataSetChanged();
}
});
binding.matList.setLayoutManager(new GridLayoutManager(this,2));
binding.matList.setAdapter(adapter);
binding.matHome.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(Materials.this,MainActivity.class);
startActivity(intent);
}
});
}
}
This is my adapter code
package com.example.motionofknowledge;
import android.content.Context;
import android.content.Intent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import com.bumptech.glide.Glide;
import java.util.ArrayList;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
public class MatAdapter extends RecyclerView.Adapter<MatAdapter.MatViewHolder>{
Context context;
ArrayList<MatModel> matModels;
public MatAdapter(Context context, ArrayList<MatModel> matModels){
this.context = context;
this.matModels = matModels;
}
#NonNull
#Override
public MatViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(context).inflate(R.layout.item_category,null);
return new MatViewHolder(view);
}
#Override
public void onBindViewHolder(#NonNull MatViewHolder holder, int position) {
MatModel model = matModels.get(position);
holder.textView.setText(model.getMatName());
Glide.with(context)
.load(model.getMatImage())
.into(holder.imageView);
holder.itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(context,Chapters.class);
intent.putExtra("matId",model.getMatId());
context.startActivity(intent);
}
});
}
#Override
public int getItemCount() {
return matModels.size();
}
public class MatViewHolder extends RecyclerView.ViewHolder{
ImageView imageView;
TextView textView;
public MatViewHolder(#NonNull View itemView) {
super(itemView);
imageView = itemView.findViewById(R.id.image);
textView = itemView.findViewById(R.id.category);
}
}
}
You did not post your adapter code, but your activity code. Anyway: I understand that you have a recyclerView with different kind of items in it (Video Lecture, Detail Notes, and more). Depending on which item the user clicks, you want to do different things.
This is done by using the onBindViewHolder method in your MatAdapter. This method does not only bind the data to the UI layout, but it should also be used to bind a click listener to the UI layout.
If you have only a few items in your RecyclerView, you could use the getItem(position) method of your adapter to find out what specific item you are dealing with within onBindViewHolder. As soon as you know what kind of item the Adapter wants to bind, you can set the according click listener.
See this suggestion:
holder.itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = null
if (model.type == VIDEO) {
intent = new Intent(context,Video.class);
} else if (model.type == DETAILS) {
intent = new Intent(context,Details.class);
} else {
...
}
intent.putExtra("matId",model.getMatId());
context.startActivity(intent);
}
});
model is the current MatModel that you want to bind.
model.type is any way to distinguish the different items. I do not know the details of the MatModel class, but you somehow need to be able to distinguish the different models, of course.

NullPointerException on FragmentActivity.onBackPressed()

I have a problem on up back icon toolbar, when i click twice to go back app crash on nullpointer exception recalling the error on my getActivity().onBackPressed();
this is the fragment:
package com.example.android.evilsecretgallery;
import android.graphics.Bitmap;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.transition.TransitionInflater;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import com.bumptech.glide.Glide;
import com.bumptech.glide.request.target.SimpleTarget;
import com.bumptech.glide.request.transition.Transition;
import com.github.chrisbanes.photoview.PhotoView;
public class ImageDetailFragment extends Fragment {
private static final String EXTRA_IMAGE = "image_item";
private static final String EXTRA_TRANSITION_NAME = "transition_name";
public ImageDetailFragment() {
// Required empty public constructor
}
public static ImageDetailFragment newInstance(ImageModel image, String transitionName) {
ImageDetailFragment fragment = new ImageDetailFragment();
Bundle args = new Bundle();
args.putParcelable(EXTRA_IMAGE, image);
args.putString(EXTRA_TRANSITION_NAME, transitionName);
fragment.setArguments(args);
return fragment;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
postponeEnterTransition();
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
setSharedElementEnterTransition(TransitionInflater.from(getContext()).inflateTransition(android.R.transition.move));
}
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_image_detail, container, false);
Toolbar toolbar = getActivity().findViewById(R.id.toolbar);
toolbar.setTitle(" ES ");
toolbar.setTitleTextAppearance(getActivity(), R.style.EvilTextAppearance);
toolbar.setNavigationOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
getActivity().onBackPressed();
}
});
return rootView;
}
#Override
public void onViewCreated(View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
final ImageModel image = getArguments().getParcelable(EXTRA_IMAGE);
String transitionName = getArguments().getString(EXTRA_TRANSITION_NAME);
final PhotoView imageView = view.findViewById(R.id.detail_image);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
imageView.setTransitionName(transitionName);
}
Glide.with(getActivity())
.asBitmap()
.load(image.getUrl())
.into(new SimpleTarget<Bitmap>() {
#Override
public void onResourceReady(#NonNull Bitmap resource, #Nullable Transition<? super Bitmap> transition) {
startPostponedEnterTransition();
imageView.setImageBitmap(resource);
}
});
}
}
that go back in this activity:
package com.example.android.evilsecretgallery;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.Toolbar;
import android.view.MenuItem;
public class PagesActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_pages);
Toolbar toolbar = findViewById(R.id.toolbar);
toolbar.setTitle(" ES ");
toolbar.setTitleTextAppearance(this, R.style.EvilTextAppearance);
setSupportActionBar(toolbar);
if (getSupportActionBar()!=null){
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setDisplayShowHomeEnabled(true);
}
getSupportFragmentManager()
.beginTransaction()
.add(R.id.content, RecyclerViewFragment.newInstance())
.commit();
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if (item.getItemId()==android.R.id.home)
finish();
return super.onOptionsItemSelected(item);
}
}
then if I go back again to this activity below it gives me the error:
package com.example.android.evilsecretgallery;
import android.content.Intent;
import android.net.Uri;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity {
ImageView cover;
Toolbar toolbar;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
toolbar = findViewById(R.id.toolbar);
toolbar.setTitle(" ES ");
toolbar.setTitleTextAppearance(this, R.style.EvilTextAppearance);
setSupportActionBar(toolbar);
cover = findViewById(R.id.cover_id);
cover.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
// Create a new intent to open the PagesActivity
Intent intent = new Intent(MainActivity.this, PagesActivity.class);
// Start the new activity
startActivity(intent);
}
});
Button siteButton = findViewById(R.id.site_button);
siteButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
String url = "http://www.evilsecret.it";
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setData(Uri.parse(url));
startActivity(intent);
}
});
}
}
I have made some experiment and if i go back from pages activity it has no problem. I have to use different method in the fragment?
try clean and rebuild your project
It worked for me.

Cannot resolve Symbol variables - Tearing my hair out

I am trying to follow a tutorial and have got stuck with what I figure to be the last error before completion.
Can someone tell me what I am doing wrong with these variables?
Including both activities below, if any other code is applicable, I am happy to provide it.
Error codes read:
Error:(21, 56) error: cannot find symbol variable pickupLine
Error:(24, 9) error: cannot find symbol variable retryButton
Error:Execution failed for task ':app:compileDebugJavaWithJavac'.
Compilation failed; see the compiler error output for details.
MainActivity.java:
package io.wavey.pickuplesson1;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Grab clean button so we can do stuff with it!
Button cleanButton = (Button) findViewById(R.id.cleanButton);
final Button dirtyButton = (Button) findViewById(R.id.dirtyButton);
final String pickupLine = "You had me at hello world";
//This is a Callback.
cleanButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
sendLine(pickupLine);
}
});
}
//Send to activity
private void sendLine(String pickupLine) {
Intent intent = new Intent(this, LineActivity.class);
intent.putExtra("Pickup Line", pickupLine);
startActivity(intent);
}
}
LineActivity.java:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_line);
Bundle pickupData = getIntent().getExtras();
if (pickupData == null) {
return;
}
String receivedPickupLine = pickupData.getString("Pickup Line");
TextView newLine = (TextView) findViewById(R.id.pickupLine);
newLine.setText(receivedPickupLine);
retryButton.setOnClicklistener (new View.OnClickListener() {
#Override
public void onClick(View v) {
finish();
}
});
}
}
LineActivity.java:

My android application cannot play again when clicking button

I'm new in android programming. My first application is an android mediaplayer.
I built two buttons : one to play a song, and another to stop it.
My application is running correctly ; the problem is that i can play and stop it, but I cant play the song again.
I tried to use setDataSource() but it triggers an error.
Here's the code ; the file is in raw/song.mp3
package com.example.test6;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.app.Activity;
import android.view.View;
import android.widget.Button;
public class MainActivity extends Activity {
MediaPlayer mp;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mp = MediaPlayer.create(this,R.raw.song);
setContentView(R.layout.activity_main);
final Button btnPlay = (Button)this.findViewById(R.id.button1);
final Button btnStop = (Button)this.findViewById(R.id.button2);
btnPlay.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
mp.start();
}
});
btnStop.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
mp.stop();
mp.reset();
if(mp.isPlaying()){
mp.stop();
}else{
mp.setDataSource("res/raw/song.mp3");
mp.prepare();
mp.start();
}
});
}
}
First of all, you don't need to set the data source manually if you're doing the creation like this: MediaPlayer.create(this, R.raw.song); Also, in that case, you don't need to call prepare() because MediaPlayer.create() does that for you.
I would suggest this kind of approach (assuming you don't want the start button to do anything if it's already playing):
Start button listener:
if (mp==null) {
mp = MediaPlayer.create(this, R.raw.song);
}
if (!mp.isPlaying()) {
mp.start();
}
Stop button listener:
if (mp!=null) {
if (mp.isPlaying()) {
mp.stop();
}
mp.release();
mp = null;
}
I didn't test this, so I'm looking forward to your response