I am trying to call a DialogFragment from my Fragment class. I have an EditText, and would like to call my DialogFragment class in the onClickListener of the EditText I have set up.
I am getting an error in the onClick with the code I have set up trying to call the DialogFragment.
I am getting an error on "show" stating "The method show(FragmentManager, String) in the type DialogFragment is not applicable for the arguments (FragmentManager, String)" and an error on "new Instance" stating "The method newInstance() is undefined for the type MyDialogFragment"
Here's my code:
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState) {
View root = (View) inflater.inflate(R.layout.fragment_profile_fragment, container, false);
setListenerOnWeight(root);
button(root);
return root;
}
public void setListenerOnWeight(View v) {
EditText Weight = (EditText) v.findViewById(R.id.Weight_up);
Weight.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
weight_frag dialog = new weight_frag.newInstance();
dialog.show(getFragmentManager(), "fragmentDialog");
}
});
}
for my DialogFragment class:
package com.the.healthescort;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.DialogFragment;
import android.content.Context;
import android.content.DialogInterface;
import android.os.Bundle;
import android.support.v4.*;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
public class weight_frag extends DialogFragment {
Context mContext;
public weight_frag() {
mContext = getActivity();
}
public static weight_frag newInstance() {
weight_frag f = new weight_frag();
return f;
}
#Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(mContext);
alertDialogBuilder.setTitle("Set Wallpaper?");
alertDialogBuilder.setMessage("Are you sure?");
//null should be your on click listener
alertDialogBuilder.setPositiveButton("OK", null);
alertDialogBuilder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
return alertDialogBuilder.create();
}
}
i think you should replace
import android.app.Fragment;
with
import android.support.v4.app.Fragment;
in your "my Fragment" class
and you should also provide a method with name newInstance in your dialogfragment class like below :
public static weight_frag newInstance(){
weight_frag frag = new weight_frag();
return frag;
}
please follow java naming conventions by using capital letter for the starting letter (WeightFragment)
Related
I've been working on a Android Project (A Basic College Information App), I have three main activities, the user goes in like, Goal/Course Select activity-> CollegeList activity-> College Details Activity. Now When I press back on College Details Activity it crashes with this Error:
Attempt to invoke virtual method 'int java.lang.String.hashCode()' on a null object reference
Below are the files/code which I think might be responsible for this.....
CollegeListActivity.java file
package com.anurag.college_information.activities;
import static com.anurag.college_information.activities.CareerGoalActivity.GOAL;
import static com.anurag.college_information.activities.CareerGoalActivity.SHARED_PREFS;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import com.anurag.college_information.R;
import com.anurag.college_information.adapters.RecyclerAdapter;
import com.anurag.college_information.models.ModelClass;
import java.util.ArrayList;
import java.util.List;
public class CollegeListActivity extends AppCompatActivity {
private RecyclerAdapter.RecyclerViewClickListener listener;
//ListView collegeList;
TextView collegeListTitle;
Button courseChange;
RecyclerView recyclerView;
LinearLayoutManager LayoutManager;
RecyclerAdapter recyclerAdapter;
List<ModelClass> cList;
String courseName;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_college_list);
collegeListTitle = findViewById(R.id.college_list_title);
courseChange = findViewById(R.id.btn_change_course);
//collegeListTitle.setText(goal + "Colleges");
collegeListTitle.setText(getIntent().getStringExtra("Title") + " Colleges");
initData();
initRecyclerView();
//collegeList = findViewById(R.id.lv_college_list);
courseChange.setTransformationMethod(null);
courseChange.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
SharedPreferences sharedPreferences = getSharedPreferences(SHARED_PREFS, MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.clear();
editor.apply();
Intent i = new Intent(CollegeListActivity.this, CareerGoalActivity.class);
startActivity(i);
//finish();
}
});
}
private void initData() {
cList = new ArrayList<>();
courseName = getIntent().getStringExtra("Title");
switch (courseName) {
case "BE/BTech":
cList.add(new ModelClass("https://images.static-collegedunia.com/public/college_data/images/campusimage/1479294300b-5.jpg", "A.P. Shah College of Engineering", "Thane", "8.0"));
break;
case "Pharmacy":
cList.add(new ModelClass("https://images.static-collegedunia.com/public/college_data/images/campusimage/14382400753.jpg", "Bombay College Of Pharmacy", "Mumbai", "9.0"));
break;
}
}
private void initRecyclerView() {
setOnClickListener();
recyclerView = findViewById(R.id.recycler_view);
LayoutManager = new LinearLayoutManager(this);
LayoutManager.setOrientation(RecyclerView.VERTICAL);
recyclerView.setLayoutManager(LayoutManager);
recyclerAdapter = new RecyclerAdapter(cList, listener);
recyclerView.setAdapter(recyclerAdapter);
}
private void setOnClickListener() {
listener = new RecyclerAdapter.RecyclerViewClickListener() {
#Override
public void onClick(View v, int position) {
Intent i = new Intent(CollegeListActivity.this, CollegeDetailsActivity.class);
startActivity(i);
}
};
}
#Override
public void onBackPressed() {
new AlertDialog.Builder(this)
.setMessage("Are you sure you want to exit?")
.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
finish();
}
})
.setNegativeButton("No", null)
.show();
}
}
RecyclerAdapter.java
package com.anurag.college_information.adapters;
import android.content.Context;
import android.content.Intent;
import android.telecom.Call;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import com.anurag.college_information.activities.CollegeDetailsActivity;
import com.anurag.college_information.models.ModelClass;
import com.anurag.college_information.R;
import com.squareup.picasso.Picasso;
import java.util.List;
public class RecyclerAdapter extends RecyclerView.Adapter<RecyclerAdapter.ViewHolder> {
private List<ModelClass> collegeList ;
private RecyclerViewClickListener listener;
List<String> imageUrl, collegeName, collegeLocation, collegeRating;
public RecyclerAdapter(List<ModelClass> collegeList, RecyclerViewClickListener listener){
this.collegeList=collegeList;
this.listener = listener;
}
#NonNull
#Override
public RecyclerAdapter.ViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.college_list_single_row, parent, false);
return new ViewHolder(view);
}
#Override
public void onBindViewHolder(#NonNull RecyclerAdapter.ViewHolder holder, int position) {
String imageLink = collegeList.get(position).getImageLink();
//int img = collegeList.get(position).getCollegeImage();
String cName = collegeList.get(position).getCollegeName();
String cRating = collegeList.get(position).getCollegeRating();
String cLocation = collegeList.get(position).getLocation();
Picasso.get().load(imageLink).into(holder.imageView);
//holder.setData(img, cName, cRating);
holder.setData(imageLink, cName, cLocation ,cRating);
}
#Override
public int getItemCount() {
return collegeList.size();
}
public class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
private ImageView imageView;
private TextView collegeName, collegeRating, collegeLocation;
public ViewHolder(#NonNull View itemView) {
super(itemView);
imageView = itemView.findViewById(R.id.college_image);
collegeName = itemView.findViewById(R.id.college_name);
collegeRating = itemView.findViewById(R.id.college_rating);
collegeLocation = itemView.findViewById(R.id.college_location);
itemView.setOnClickListener(this);
}
public void setData(String imageLink, String cName, String cLocation, String cRating) {
//imageView.setImageResource(img);
Picasso.get().load(imageLink).error(R.drawable.error).into(imageView);
collegeName.setText(cName);
collegeRating.setText(cRating);
collegeLocation.setText(cLocation);
}
#Override
public void onClick(View v) {
listener.onClick(v, getAdapterPosition());
Intent i = new Intent(v.getContext(), CollegeDetailsActivity.class);
i.putExtra("collegeImage", collegeList.get(getAdapterPosition()).getImageLink());
i.putExtra("collegeName", collegeList.get(getAdapterPosition()).getCollegeName());
i.putExtra("collegeRating", collegeList.get(getAdapterPosition()).getCollegeRating());
i.putExtra("collegeLocation", collegeList.get(getAdapterPosition()).getLocation());
v.getContext().startActivity(i);
}
}
public interface RecyclerViewClickListener{
void onClick(View v, int position);
}
}
CollegeDetailsActivity.java
package com.anurag.college_information.activities;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import androidx.appcompat.app.AppCompatActivity;
import com.anurag.college_information.R;
import com.squareup.picasso.Picasso;
public class CollegeDetailsActivity extends AppCompatActivity {
Button btnApply;
ImageView dCollegeImage;
TextView dCollegeName, dCollegeRating, dCollegeLocation;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_college_details);
dCollegeImage = findViewById(R.id.details_college_image);
dCollegeName = findViewById(R.id.details_college_name);
dCollegeRating = findViewById(R.id.details_college_rating);
dCollegeLocation = findViewById(R.id.details_college_location);
btnApply = findViewById(R.id.btn_apply);
Intent i = getIntent();
String cn = i.getStringExtra("collegeName");
String cr = i.getStringExtra("collegeRating");
String ci = i.getStringExtra("collegeImage");
String cl = i.getStringExtra("collegeLocation");
Picasso.get().load(ci).error(R.drawable.error).into(dCollegeImage);
dCollegeName.setText(cn);
dCollegeRating.setText(cr);
dCollegeLocation.setText(cl);
btnApply.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(getApplicationContext(), "The institute will be notified, of your application", Toast.LENGTH_LONG).show();
Toast.makeText(getApplicationContext(), "The college will contact you, Thank you", Toast.LENGTH_LONG).show();
}
});
}
#Override
public void onBackPressed() {
Intent i = new Intent(CollegeDetailsActivity.this, CollegeListActivity.class);
startActivity(i);
}
}
This is the Error Screenshot:
I'm pretty new to android I've just worked on just 4 to 5 projects,
Any Assistance will be appreciated, Thank You
The commented Out code, is just a normal listview I implemented just In Case, I have to remove the recycler view.
This will probably go away if you don't override onBackPressed in CollegeDetailsActivity. Instead of going back to an activity that had a valid "Title" string extra, the code you posted will go to a new activity where "Title" isn't defined, then get a NullPointerException since courseName will be null in initData (which the error message tells you results in an error on line 81 in that method). Using a null string in a switch results in that type of error
Just remove your onBackPressed entirely in CollegeDetailsActivity.
I'm trying to create a function that once a user clicks on the recycler view, a dialog box will pop out but I am stuck on the error as mentioned below. When I try to initialize AlertDialog.build and put this as the parameter, it shows an error. I had tried with a few other parameters like context, getActivity. But the error is still the same.
The code below is my full code
package com.example.tuitioncentre;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.database.Observable;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import com.firebase.ui.database.FirebaseRecyclerAdapter;
import com.firebase.ui.database.FirebaseRecyclerOptions;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.firestore.DocumentSnapshot;
public class myadapter_tutorlist extends FirebaseRecyclerAdapter<User,myadapter_tutorlist.myviewholder> {
AlertDialog.Builder builder;
public myadapter_tutorlist(#NonNull FirebaseRecyclerOptions<User> options) {
super(options);
}
#Override
protected void onBindViewHolder(#NonNull final myviewholder holder, int position, #NonNull final User model) {
holder.name.setText("Tutor's Name:" + model.getUsername());
holder.phone.setText("Phone No:" + model.getPhone());
holder.email.setText("Email:" + model.getEmail());
holder.status.setText("Status: " + model.getActive().toString());
builder = new AlertDialog.Builder(this);
holder.itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(final View v) {
//Toast.makeText(v.getContext(),model.getUsername(),Toast.LENGTH_SHORT).show();
builder.setMessage(R.string.dialog_message) .setTitle(R.string.dialog_title);
builder.setMessage("Do you want to activate tutor account ?")
.setCancelable(false)
.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
Toast.makeText(v.getContext(),"you choose yes action for alertbox", Toast.LENGTH_SHORT).show();
}
})
.setNegativeButton("No", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
// Action for 'NO' Button
dialog.cancel();
Toast.makeText(v.getContext(),"you choose no action for alertbox", Toast.LENGTH_SHORT).show();
}
});
//Creating dialog box
AlertDialog alert = builder.create();
//Setting the title manually
alert.setTitle("AlertDialogExample");
alert.show();
}
});
}
#NonNull
#Override
public myviewholder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
//put singlerow xml into view holder
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.singlerow,parent,false);
return new myviewholder(view);
}
class myviewholder extends RecyclerView.ViewHolder{
TextView name,phone,email,status;
public myviewholder(#NonNull View itemView) {
super(itemView);
name=(TextView)itemView.findViewById(R.id.nametext);
phone=(TextView)itemView.findViewById(R.id.phonetext);
email=(TextView)itemView.findViewById(R.id.emailtext);
status=(TextView)itemView.findViewById(R.id.statustext);
}
}
}
Passing "this" to AlertDialog.Builder(this); won't work as you're trying to pass a reference of your Adapter.
There are two correct ways to achieve this:
Add a variable to reference your Activity like Activity mActivity; in your Adapter class. Then, in your Activity class where you're initializing the Adapter, you can pass your activity context as "this". You can achieve it either with a constructor in the Adapter class or in your Activity class use your adapter instance once it is initialized to access the mActivity variable and set it.
Alternatively, you can use a view interface and implement it in your activity, override the method to show the AlertDialog in your activity. Then add a reference variable of that interface in your Adapter like SomeInterface mInfterface; and initialize it in your Activity class the same way mentioned above. Then you can just call that method to show the AlertDialog and pass the data to that method from the Adapter to show all information like -
mInterface.showAlertDialog(model);
first create this class:
class RecyclerItemClickListener extends RecyclerView.SimpleOnItemTouchListener {
interface OnRecyclerClickListener{
void onItemClick(View view, int position);
}
private final OnRecyclerClickListener mListener;
private final GestureDetectorCompat mGestureDetector;
public RecyclerItemClickListener(Context context, final RecyclerView recyclerView,
OnRecyclerClickListener listener) {
mListener = listener;
mGestureDetector = new GestureDetectorCompat(context, new GestureDetector.SimpleOnGestureListener(){
#Override
public boolean onSingleTapUp(MotionEvent e) {
View childView = recyclerView.findChildViewUnder(e.getX(), e.getY());
if (childView != null && mListener != null){
Log.d(TAG, "onSingleTapUp: calling listener.onItemClick");
mListener.onItemClick(childView, recyclerView.getChildAdapterPosition(childView));
}
return true;
}
});
}
#Override
public boolean onInterceptTouchEvent(#NonNull RecyclerView rv, #NonNull MotionEvent e) {
if (mGestureDetector != null){
boolean result = mGestureDetector.onTouchEvent(e);
return result;
} else {
return false;
}
}
}
and in MainActivity:
in onCreate method: first define recyclerView variable by findviewbyid() then:
recyclerView.addOnItemTouchListener(new RecyclerItemClickListener(this, recyclerView, this));
then implement onItemClick() method. you can define alert dialog here:
#Override
public void onItemClick(View view, int position) {
Toast.makeText(this, "normal tap on position " + position, Toast.LENGTH_SHORT).show();
}
First pass the context from the Activity or Fragment:
For activity:
myadapter_tutorlist(options, this);
For Fragment:
myadapter_tutorlist(options, getActivity());
Then create a Context variable in side the Adapter class:
public class myadapter_tutorlist extends FirebaseRecyclerAdapter<User,myadapter_tutorlist.myviewholder> {
AlertDialog.Builder builder;
Context context;
public myadapter_tutorlist(#NonNull FirebaseRecyclerOptions<User> options) {
super(options);
this.context = context;
}
Now you can pass this context to your AlertDialog
builder = new AlertDialog.Builder(context);
When i declare the array adapter up as golbal public the app crash when i just start it
but when i declare it inside the onClick method it works fine
i need to know that happen ?
package com.rafahya.myapplication;
import android.content.DialogInterface;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.Toast;
import java.util.ArrayList;
public class MainActivity extends AppCompatActivity {
public ArrayAdapter<String> arrayAdapter = new ArrayAdapter<String>(MainActivity.this , android.R.layout.simple_list_item_1 ,arrayList);
public ArrayList<String> arrayList = new ArrayList<String>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
arrayList.add("momen");
arrayList.add("ahmed");
arrayList.add("Amin");
Button button = (Button)findViewById(R.id.ok);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
AlertDialog.Builder momen = new AlertDialog.Builder(MainActivity.this)
.setTitle("Enter the Zip Code")
.setAdapter(arrayAdapter , new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
Toast.makeText(MainActivity.this , "Momen" ,Toast.LENGTH_LONG).show();
}
});
momen.show();
}
});
}
}
public ArrayAdapter<String> arrayAdapter = new ArrayAdapter<String>(MainActivity.this , android.R.layout.simple_list_item_1 ,arrayList);
With this line you are trying to access MainActivity before it is initialised. When you type this in the onClick it will be executed when you are inside onCreate and the class is already initialised.
As to how to fix it- First declare the variable
public ArrayAdapter<String> arrayAdapter;
and then inside the onCreate
arrayAdapter = new ArrayAdapter<String>(MainActivity.this , android.R.layout.simple_list_item_1 ,arrayList);
I am creating simple contacts app in android. MainActivity consist of listview displaying image and name. I am using a model for setting and getting data and ArrayList to pass the data to next activity. When I click on single listview item. It should display next activity displaying contact details.
MainActivity.java
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import java.util.ArrayList;
public class MainActivity extends AppCompatActivity {
String[] name={
"Adam",
"John",
"Jasmine"
};
int[] image={
R.drawable.img1,
R.drawable.img2,
R.drawable.img3
};
String[] mobile_no={
"03349875429",
"03458294792",
"03318245801",
};
String[] email={
"adam123#yahoo.com",
"john123#gmail.com",
"jasmine456#hotmail.com"
};
String[] url={
"https://www.google.com.pk/",
"https://www.google.com.pk/",
"https://www.google.com.pk/"
};
ContactModel contact;
ArrayList<ContactModel> contact_list=new ArrayList<ContactModel>();
ListView ls;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ls=(ListView)findViewById(R.id.listView);
for(int i=0;i<name.length;i++){
contact=new ContactModel();
contact.setImage(image[i]);
contact.setName(name[i]);
contact.setMobile_no(mobile_no[i]);
contact.setEmail(email[i]);
contact.setUrl(url[i]);
contact_list.add(contact);
}
CustomBaseAdapter adapter=new CustomBaseAdapter(this,contact_list);
ls.setAdapter(adapter);
ls.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
ContactModel contacts=contact_list.get(i);
Intent intent=new Intent(getApplicationContext(),ContactDetails.class);
intent.putExtra("contacts",contacts);
startActivity(intent);
}
});
}
}
CustomeBaseAdapter.java
import android.app.Activity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;
import java.util.ArrayList;
public class CustomBaseAdapter extends BaseAdapter {
Activity activity;
ArrayList<ContactModel> contact;
LayoutInflater inflator;
TextView name;
ImageView image;
public CustomBaseAdapter(Activity activity, ArrayList<ContactModel> contact) {
this.activity=activity;
this.contact=contact;
inflator=activity.getLayoutInflater();
}
#Override
public int getCount() {
return contact.size();
}
#Override
public Object getItem(int i) {
return contact.get(i);
}
#Override
public long getItemId(int i) {
return i;
}
#Override
public View getView(int i, View view, ViewGroup viewGroup) {
View v=view;
if(view==null){
v=inflator.inflate(R.layout.contact_list_,null);
}
name=(TextView)v.findViewById(R.id.name_textView);
image=(ImageView)v.findViewById(R.id.imageView);
ContactModel c=(ContactModel) getItem(i);
name.setText(c.getName());
image.setImageResource(c.getImage());
return v;
}
}
ContactDetails.java
import android.content.Intent;
import android.net.Uri;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
public class ContactDetails extends AppCompatActivity {
ImageView imageView;
TextView nameView;
TextView mobileView;
TextView emailtextview;
TextView urlView;
ImageView callButton;
ImageView messageButton;
ImageView emailButton;
ImageView websiteButton;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_contact_details);
Intent intent=getIntent();
final ContactModel contacts=(ContactModel)intent.getSerializableExtra("contacts");
imageView=(ImageView)findViewById(R.id.imageView);
nameView=(TextView)findViewById(R.id.name_view);
mobileView=(TextView)findViewById(R.id.number_view);
emailtextview=(TextView)findViewById(R.id.email_textview);
urlView=(TextView)findViewById(R.id.url_textview);
//Buttons
callButton=(ImageView)findViewById(R.id.callButton);
messageButton=(ImageView)findViewById(R.id.message_view);
emailButton=(ImageView)findViewById(R.id.email_imageview);
websiteButton=(ImageView)findViewById(R.id.url_imageview);
imageView.setImageResource(contacts.getImage());
nameView.setText(contacts.getName());
mobileView.setText(contacts.getMobile_no());
emailtextview.setText(contacts.getEmail());
urlView.setText(contacts.getUrl());
}
}
ContactModel simply consist of setter and getter methods. Call Button etc functionality is not implemented yet. No error is displayed but when I run the project it displays 1 error: Error:java.lang.NullPointerException (no error message)
logcat:
09-25 05:09:54.006 1745-1775/system_process E/BluetoothAdapter: Bluetooth binder is null
09-25 05:11:00.001 1745-1773/system_process I/ProcessStatsService: Prepared write state in 0ms
09-25 05:16:38.974 98-98/? D/Genyd: Received Set Clipboard
09-25 05:16:38.974 98-98/? D/Genymotion: Received Set Clipboard
you can do this to resolve your problem:
ls.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
//ContactModel contacts=new ContactModel();//here you did mistake
Intent intent=new Intent(getApplicationContext(),ContactDetails.class);
intent.putExtra("contacts",(Serializable) adapterView.getSelectedItem());
startActivity(intent);
}
});
In ls.setOnItemClickListener, you're passing ContactModel contacts=new ContactModel(); which is technically a blank object of ContactModel.
Now, when you're trying to set data in ContactDetails.java from that blank object that you got from Intent like this,
imageView.setImageResource(contacts.getImage());
nameView.setText(contacts.getName());
the contact object has no image or name (or other attributes for that matter) that has been previously set on it. Hence, you're getting a null pointer exception.
So, change it like below and your problem should get away.
ls.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
ContactModel contacts= contact_list.get(i);
Intent intent=new Intent(getApplicationContext(),ContactDetails.class);
Bundle bundle = new Bundle();
bundle.putSerializable("contacts",contacts);
intent.putExtras(bundle);
startActivity(intent);
}
});
And in ContactDetails.java, get the object like this.
Intent intent=getIntent();
Bundle bundle = intent.getExtras();
final ContactModel contacts=(ContactModel)bundle.getSerializable("contacts");
I have an Error on Public View onCreateView on getApplicationContext seems it wont work at my HomeFragment, but when I try this at my MainAcitivity it work. does anyone encounter this?
Thanks in Advance!
Here`s my Code:
package com.thesis.artificialintelligence;
import android.app.Activity;
import android.os.Bundle;
import android.speech.tts.TextToSpeech;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import java.util.Locale;
public class HomeFragment extends Fragment {
private TextView resultTEXT;
private TextView resultTEXT2;
TextToSpeech t1;
private String package_calculator = "com.android.calculator2";
private String class_calculator ="com.android.calculator2.Calculator";
private String package_camera = "com.android.camera";
private String class_camera ="com.android.camera.Camera";
private String package_contacts = "com.android.contacts";
private String class_contacts = "com.android.contacts.Contacts";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_home, container, false);
// Inflate the layout for this fragment
rootView.findViewById(R.id.TVresult);
rootView.findViewById(R.id.TVresult2);
t1 = new TextToSpeech(getApplicationContext(), new TextToSpeech.OnInitListener() // There`s an Error here at getApplicationContext()
{
#Override
public void onInit(int status)
{
if(status != TextToSpeech.ERROR)
{
t1.setLanguage(Locale.UK);
}
}
});
return rootView;
}
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
}
#Override
public void onDetach()
{
super.onDetach();
}
}
Fragments do not have a getApplicationContext() method.
TextToSpeech only needs a context so you can replace it with getActivity().
If you really want the application context do getActivity().getApplicationContext()
Dear you can get Context using
getActivity().getApplicationContext();
If you are using fragment than replace getApplicationContext() to getActivity() and getContext().