The app is supposed to open a new activity by clicking RecyclerView. but when I try to click on my RecyclerView data, it gives the following error:
java.lang.NullPointerException: Attempt to invoke virtual method 'void android.app.Activity.startActivityForResult(android.content.Intent, int)' on a null object reference
at com.example.studyreminder.CustomAdapter$1.onClick(CustomAdapter.java:69)
I'm using fragments if that makes any difference.
I don't understand how to fix so if anyone knows it will be appreciated.
Class where the error is at:
public class CustomAdapter extends RecyclerView.Adapter<CustomAdapter.myViewHolder> {
private Context context;
private ArrayList task_id, task_subject, task_description, task_due_date;
private Activity activity;
ImageButton deleteTask;
String task;
CustomAdapter(Context context, ArrayList task_id, ArrayList task_subject, ArrayList task_description, ArrayList task_due_date){
this.context = context;
this.task_id = task_id;
this.task_description = task_description;
this.task_subject = task_subject;
this.task_due_date = task_due_date;
}
#NonNull
#Override
public myViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
LayoutInflater inflater = LayoutInflater.from (context);
View view = inflater.inflate(R.layout.to_do_list, parent, false);
return new myViewHolder(view);
}
#RequiresApi(api = Build.VERSION_CODES.M)
#Override
public void onBindViewHolder(#NonNull myViewHolder holder, final int position) {
holder.taskid_txt.setText(String.valueOf(task_id.get(position)));
holder.taskSubject_txt.setText(String.valueOf(task_subject.get(position)));
holder.taskDescription_txt.setText(String.valueOf(task_description.get(position)));
holder.taskDate_txt.setText(String.valueOf(task_due_date.get(position)));
holder.mainLayout.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(context, UpdateActivity.class);
intent.putExtra("id", String.valueOf(task_id.get(position)));
intent.putExtra("subject", String.valueOf(task_subject.get(position)));
intent.putExtra("description", String.valueOf(task_description.get(position)));
intent.putExtra("dueDate", String.valueOf(task_due_date.get(position)));
activity.startActivityForResult(intent, 1);
}
});
}
#Override
public int getItemCount() {
return task_id.size();
}
public class myViewHolder extends RecyclerView.ViewHolder {
TextView taskid_txt, taskSubject_txt, taskDescription_txt, taskDate_txt;
LinearLayout mainLayout;
public myViewHolder(#NonNull View itemView) {
super(itemView);
taskid_txt = itemView.findViewById(R.id.taskid_txt);
taskSubject_txt = itemView.findViewById(R.id.taskSubject_txt);
taskDescription_txt = itemView.findViewById(R.id.taskDescription_txt);
taskDate_txt = itemView.findViewById(R.id.taskDate_txt);
mainLayout = itemView.findViewById(R.id.mainLayout);
}
}
}
The activity I'm trying to open:
public class UpdateActivity extends AppCompatActivity {
EditText title_input, author_input, pages_input;
Button addBtn2, delete_button;
EditText descEntry2, dateEntry2;
Spinner sp2;
String id, description, dueDate, subject;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_update);
descEntry2 = findViewById(R.id.descEntry2);
dateEntry2 = findViewById(R.id.dateEntry2);
addBtn2= findViewById(R.id.addbtn2);
sp2 = findViewById(R.id.subjectEntry2);
delete_button = findViewById(R.id.delete_button);
//First we call this
getAndSetIntentData();
//Set actionbar title after getAndSetIntentData method
ActionBar ab = getSupportActionBar();
if (ab != null) {
ab.setTitle(subject);
}
addBtn2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
//And only then we call this
MyDatabase myDB = new MyDatabase(UpdateActivity.this);
description = descEntry2.getText().toString().trim();
dueDate =dateEntry2.getText().toString().trim();
subject = sp2.getSelectedItem().toString().trim();
myDB.updateData(id, subject, description, dueDate);
}
});
delete_button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
confirmDialog();
}
});
}
void getAndSetIntentData(){
if(getIntent().hasExtra("id")
&& getIntent().hasExtra("subject")
&& getIntent().hasExtra("description")
&& getIntent().hasExtra("dueDate")){
//Getting Data from Intent
id = getIntent().getStringExtra("id");
subject = getIntent().getStringExtra("subject");
description = getIntent().getStringExtra("description");
dueDate = getIntent().getStringExtra("dueDate");
//Setting Intent Data
title_input.setText(subject);
author_input.setText(description);
pages_input.setText(dueDate);
Log.d("stev", subject+" "+description+" "+dueDate);
}else{
Toast.makeText(this, "No data.", Toast.LENGTH_SHORT).show();
}
}
void confirmDialog(){
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Delete " + subject + " Task?");
builder.setMessage("Are you sure you want to delete this " + subject + " task?");
builder.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
MyDatabase myDB = new MyDatabase(UpdateActivity.this);
myDB.deleteOneRow(subject);
finish();
}
});
builder.setNegativeButton("No", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
}
});
builder.create().show();
}
}
XML code for the UpdateActivity:
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:id="#+id/addTasktxt"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="150dp"
android:layout_marginBottom="50dp"
android:text="#string/addTask"
android:textSize="25dp"
android:textStyle="bold"
app:layout_constraintBottom_toTopOf="#+id/descEntry2"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<Button
android:id="#+id/addbtn2"
android:layout_width="155dp"
android:layout_height="57dp"
android:layout_marginTop="50dp"
android:layout_marginBottom="136dp"
android:text="Update"
android:textAllCaps="false"
android:textSize="20dp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.488"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/dateEntry2"
/>
<Spinner
android:id="#+id/subjectEntry2"
android:layout_width="228dp"
android:layout_height="55dp"
android:popupBackground="#5c5c5c"
android:textAlignment="center"
app:layout_constraintBottom_toTopOf="#+id/dateEntry2"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent" />
<EditText
android:id="#+id/descEntry2"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginStart="50dp"
android:layout_marginEnd="50dp"
android:layout_marginBottom="50dp"
android:ems="10"
android:hint="What needs to be done?"
android:inputType="text"
app:layout_constraintBottom_toTopOf="#+id/subjectEntry2"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.0"
app:layout_constraintStart_toStartOf="parent" />
<EditText
android:id="#+id/dateEntry2"
android:layout_width="104dp"
android:layout_height="47dp"
android:layout_marginStart="125dp"
android:layout_marginTop="50dp"
android:layout_marginEnd="125dp"
android:ems="10"
android:hint="#string/taskDueDate"
android:inputType="phone"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.491"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/subjectEntry2" />
<Button
android:id="#+id/delete_button"
android:layout_width="156dp"
android:layout_height="51dp"
android:text="Delete"
android:textAllCaps="false"
android:textSize="20sp"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.486"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/addbtn2" />
</androidx.constraintlayout.widget.ConstraintLayout>
you have not intialized private Activity activity; in CustomAdapter constructor.
either initialize it in ctor or try the snippet below:
try replacing:
holder.mainLayout.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(context, UpdateActivity.class);
intent.putExtra("id", String.valueOf(task_id.get(position)));
intent.putExtra("subject", String.valueOf(task_subject.get(position)));
intent.putExtra("description", String.valueOf(task_description.get(position)));
intent.putExtra("dueDate", String.valueOf(task_due_date.get(position)));
activity.startActivityForResult(intent, 1);
}
});
with:
holder.mainLayout.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Context myContext = context == null ? view.getContext() : context;
Intent intent = new Intent(, UpdateActivity.class);
intent.putExtra("id", String.valueOf(task_id.get(position)));
intent.putExtra("subject", String.valueOf(task_subject.get(position)));
intent.putExtra("description", String.valueOf(task_description.get(position)));
intent.putExtra("dueDate", String.valueOf(task_due_date.get(position)));
(activity == null ? (Activity)myContext : activity) .startActivityForResult(intent, 1);
}
});
Try with the following code. I think your activity object is null. You have not initialize your activity object
context.startActivity(intent);
//findViewById() is missing for below variable in UpdateActivity
EditText title_input, author_input, pages_input;
Related
While I am capable of deleteing a selected contact from sqlite database I can't seem to properly update the recyclerview when I do it. I tried using the notifyDataSetChanged() command in the custom adapter but it does not give any results.
This is the customAdapter.
public class CustomAdapter extends RecyclerView.Adapter<CustomAdapter.MyViewHolder> {
private Context context;
public ArrayList Contact_id, Contact_Name, Contact_number;
public ImageView mDelete, mMakeCall, mSendText;
public String Latitude="0",Longitude="0";
DatabaseHelper myDB;
public interface OnItemClickListener {
void onDeleteClick(int position);
}
CustomAdapter(Context context, ArrayList Contact_id, ArrayList Contact_Name, ArrayList Contact_number,String mLatitude,String mLongitude) {
this.context = context;
this.Contact_id = Contact_id;
this.Contact_Name = Contact_Name;
this.Contact_number = Contact_number;
this.Latitude= mLatitude;
this.Longitude=mLongitude;
}
#NonNull
#Override
public MyViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
LayoutInflater inflater = LayoutInflater.from(context);
View view = inflater.inflate(R.layout.cardview_contact_item, parent, false);
return new MyViewHolder(view);
}
#Override
public void onBindViewHolder(#NonNull MyViewHolder holder, int position) {
holder.Contact_id_txt.setText(String.valueOf(Contact_id.get(position)));
holder.Contact_Name_txt.setText(String.valueOf(Contact_Name.get(position)));
holder.Contact_Number_txt.setText(String.valueOf(Contact_number.get(position)));
}
#Override
public int getItemCount() {
return Contact_id.size();
}
public class MyViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
TextView Contact_id_txt, Contact_Name_txt, Contact_Number_txt;
public MyViewHolder(#NonNull View itemView) {
super(itemView);
mDelete = itemView.findViewById(R.id.Cardview_delete);
mMakeCall = itemView.findViewById(R.id.Cardview_MakeCall);
mSendText = itemView.findViewById(R.id.Cardview_MakeText);
Contact_Name_txt = itemView.findViewById(R.id.CardView_Name);
Contact_Number_txt = itemView.findViewById(R.id.CardView_Number);
Contact_id_txt = itemView.findViewById(R.id.cardview_Contact_Id);
SharedPreferences mPreference = PreferenceManager.getDefaultSharedPreferences(context);
SharedPreferences.Editor editor = mPreference.edit();
mDelete.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
//int id= Integer.parseInt(Contact_id.getText.toString());
int contactId = Integer.parseInt(Contact_id_txt.getText().toString());
Toast.makeText(context, "int id ="+contactId+"Contact id ="+Contact_id, Toast.LENGTH_SHORT).show();
DatabaseHelper databaseHelper = new DatabaseHelper(context);
boolean success = databaseHelper.deleteOne(contactId);
Toast.makeText(context, "Contact Deleted", Toast.LENGTH_SHORT).show();
notifyDataSetChanged();
}
});
mMakeCall.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Toast.makeText(context, "Calling Contact", Toast.LENGTH_SHORT).show();
Intent callIntent = new Intent(Intent.ACTION_CALL);
String phonenumber = Contact_Number_txt.getText().toString();
callIntent.setData(Uri.parse("tel:" + phonenumber));
try {
context.startActivity(callIntent);
} catch (Exception ex) {
Toast.makeText(context, "Call Failed", Toast.LENGTH_SHORT).show();
ex.printStackTrace();
}
}
});
mSendText.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
//
Intent smsIntent = new Intent(Intent.ACTION_SENDTO);
String phonenumber = Contact_Number_txt.getText().toString();
try {
SmsManager mySmsManager = SmsManager.getDefault();
mySmsManager.sendTextMessage(phonenumber, null, "I NEED HELP AT LATITUDE:" + Latitude + "LONGITUDE" + Longitude+" https://www.google.com/maps/search/?api=1&query="+Latitude+","+Longitude, null, null);
Toast.makeText(context, "Alert Message Sent", Toast.LENGTH_SHORT).show();
Toast.makeText(context, "LATITUDE:" + Latitude, Toast.LENGTH_SHORT).show();
Toast.makeText(context, "LONGITUDE:" + Longitude, Toast.LENGTH_SHORT).show();
}
catch (Exception e)
{
Toast.makeText(context, "Something went wrong/Fields are Empty", Toast.LENGTH_SHORT).show();
}
//Toast.makeText(context,"The number is "+phonenumber, Toast.LENGTH_SHORT).show();
}
});
}//End of OnCreate
#Override
public void onClick(View view) {
}
}
//public void removeItem(int position){}
}
It works fine but only updates after I exit and enter the mainActivity one time.
I tried implementing the notifyDataSetChanged() method in the mainactivity itself however I get a nullpointerexception when I do it.
ImageView mDelete;
mDelete = findViewById(R.id.Cardview_delete);
mDelete.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
//int id= Integer.parseInt(Contact_id.getText.toString());
customAdapter.notifyDataSetChanged();
}
});
This is the error code
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.rakshakmk1/com.example.rakshakmk1.MainActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.ImageView.setOnClickListener(android.view.View$OnClickListener)' on a null object reference
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3270)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3409)
at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:83)
at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:135)
at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:95)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2016)
at android.os.Handler.dispatchMessage(Handler.java:107)
at android.os.Looper.loop(Looper.java:214)
at android.app.ActivityThread.main(ActivityThread.java:7356)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:492)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:930)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.ImageView.setOnClickListener(android.view.View$OnClickListener)' on a null object reference
at com.example.rakshakmk1.MainActivity.onCreate(MainActivity.java:150)
at android.app.Activity.performCreate(Activity.java:7802)
at android.app.Activity.performCreate(Activity.java:7791)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1299)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3245)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3409)
at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:83)
at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:135)
at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:95)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2016)
at android.os.Handler.dispatchMessage(Handler.java:107)
at android.os.Looper.loop(Looper.java:214)
at android.app.ActivityThread.main(ActivityThread.java:7356)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:492)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:930)
XML Layout : RecyclerView/Cardview
<?xml version="1.0" encoding="utf-8"?>
<androidx.cardview.widget.CardView xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="5dp">
<androidx.constraintlayout.widget.ConstraintLayout
android:layout_width="match_parent"
android:layout_height="102dp"
>
<ImageView
android:id="#+id/Cardview_bg"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:srcCompat="#drawable/dialog_rounded_bg"
tools:layout_editor_absoluteX="0dp"
tools:layout_editor_absoluteY="0dp" />
<ImageView
android:id="#+id/Cardview_MakeText"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="1.0"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="1.0"
app:srcCompat="#drawable/ic_location_icon_final" />
<ImageView
android:id="#+id/Cardview_delete"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.981"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.05"
app:srcCompat="#drawable/ic_delete_circle_icon_final" />
<TextView
android:id="#+id/CardView_Name"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Emergency Contact"
android:textColor="#000000"
android:textSize="30sp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.101"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.259"
android:paddingRight="50sp"/>
<TextView
android:id="#+id/CardView_Number"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Number"
android:textColor="#858585"
android:textSize="18sp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.079"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.794" />
<ImageView
android:id="#+id/Cardview_MakeCall"
android:layout_width="37dp"
android:layout_height="36dp"
app:layout_constraintBottom_toBottomOf="#+id/Cardview_MakeText"
app:layout_constraintEnd_toStartOf="#+id/Cardview_MakeText"
app:layout_constraintHorizontal_bias="0.974"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="#+id/Cardview_MakeText"
app:layout_constraintVertical_bias="0.444"
app:srcCompat="#drawable/ic_call_icon_final" />
<TextView
android:id="#+id/cardview_Contact_Id"
android:layout_width="23dp"
android:layout_height="15dp"
android:text="TextView"
app:layout_constraintBottom_toTopOf="#+id/CardView_Name"
app:layout_constraintEnd_toStartOf="#+id/Cardview_delete"
app:layout_constraintHorizontal_bias="0.469"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.0" />
</androidx.constraintlayout.widget.ConstraintLayout>
</androidx.cardview.widget.CardView>
XML Layout : MainActivity
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#drawable/gradient_background"
tools:context=".MainActivity">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#drawable/activity_rounded_bg"
android:layout_marginTop="50dp">
<androidx.recyclerview.widget.RecyclerView
android:id="#+id/RecyclerView"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:clipToPadding="true"
android:paddingHorizontal="0dp"
android:paddingTop="10dp"
tools:layout_editor_absoluteX="0dp"
tools:layout_editor_absoluteY="67dp"
tools:listitem="#layout/cardview_contact_item">
</androidx.recyclerview.widget.RecyclerView>
</RelativeLayout>
<ImageButton
android:id="#+id/btnAddContact"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="#00FFFFFF"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.498"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="1.0"
app:srcCompat="#drawable/ic_add_icon" />
</androidx.constraintlayout.widget.ConstraintLayout>
This is the MainActivity where the arraylist were created.
public class MainActivity extends AppCompatActivity {
private static final String TAG = "MainActivity";
//widgets
public ImageButton eAddContact;
RecyclerView recyclerView;
DatabaseHelper myDB;
ArrayList<String> Contact_id, Contact_Name, Contact_Number;
CustomAdapter customAdapter;
Button btnEnterContact;
private FusedLocationProviderClient fusedLocationProviderClient;
//Google's api for location services.
//private final int REQUEST_CHECK_CODE=8989;
private LocationSettingsRequest.Builder builder;
private String mLatitude,mLongitude;
private static final int REQUEST_SMS = 0;
private static final int REQUEST_LOCATION = 1;
private static final int REQUEST_CALL =2;
Intent mIntent;
LocationManager locationManager;
LocationRequest locationRequest;
LocationCallback locationCallback;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//permissions
if(ContextCompat.checkSelfPermission(this,Manifest.permission.SEND_SMS)!=PackageManager.PERMISSION_GRANTED)
{
//if permission is not granted then check if user has denied
if(ActivityCompat.shouldShowRequestPermissionRationale(this,Manifest.permission.SEND_SMS)){
}else
{
//popup for asking permission
ActivityCompat.requestPermissions(this,new String[]{Manifest.permission.SEND_SMS},REQUEST_SMS);
}
}
if(ContextCompat.checkSelfPermission(this,Manifest.permission.ACCESS_FINE_LOCATION)!=PackageManager.PERMISSION_GRANTED)
{
//if permission is not granted then check if user has denied
if(ActivityCompat.shouldShowRequestPermissionRationale(this,Manifest.permission.ACCESS_FINE_LOCATION)){
}else
{
//popup for asking permission
ActivityCompat.requestPermissions(this,new String[]{Manifest.permission.ACCESS_FINE_LOCATION},REQUEST_LOCATION);
}
}
if(ContextCompat.checkSelfPermission(this,Manifest.permission.CALL_PHONE)!=PackageManager.PERMISSION_GRANTED)
{
//if permission is not granted then check if user has denied
if(ActivityCompat.shouldShowRequestPermissionRationale(this,Manifest.permission.CALL_PHONE)){
}else
{
//popup for asking permission
ActivityCompat.requestPermissions(this,new String[]{Manifest.permission.CALL_PHONE},REQUEST_CALL);
}
}
eAddContact = findViewById(R.id.btnAddContact);
eAddContact.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Log.d(TAG, "onClick:opening dialog");
Dialog_AddContact dialog = new Dialog_AddContact();
dialog.show(getSupportFragmentManager(), "Add Contact Dialog");
}
});
//Toast.makeText(getApplicationContext(),"##",Toast.LENGTH_SHORT).show();
myDB = new DatabaseHelper(MainActivity.this);
Contact_id = new ArrayList<>();
Contact_Name = new ArrayList<>();
Contact_Number = new ArrayList<>();
recyclerView = findViewById(R.id.RecyclerView);
Cursor cursor= myDB.getEveryone();
customAdapter = new CustomAdapter(MainActivity.this, Contact_id, Contact_Name, Contact_Number,mLatitude,mLongitude);
//set all the properties of LocationRequest
locationRequest = new LocationRequest();
//how often does location check occur
locationRequest.setInterval(1000*30);
locationRequest.setFastestInterval(1000*50);
locationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
//Display cardview data
recyclerView.setAdapter(customAdapter);
recyclerView.setLayoutManager(new LinearLayoutManager(MainActivity.this));
customAdapter.notifyDataSetChanged();
//update gps data
updateGPS();
storeDataInArrays();
/*
ImageView mDelete;
mDelete = findViewById(R.id.Cardview_delete);
mDelete.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
//int id= Integer.parseInt(Contact_id.getText.toString());
customAdapter.notifyDataSetChanged();
}
});
*/
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
//will check requestCode
switch(requestCode)
{
case REQUEST_SMS:
{
//check if length of grantResults is greater than 0 and equal to PERMISSION_GRANTED
if(grantResults.length>0&&grantResults[0]==PackageManager.PERMISSION_GRANTED)
{
Toast.makeText(this,"SMS Permission Granted",Toast.LENGTH_LONG).show();
}
else
{
Toast.makeText(this,"SMS Permission Denied",Toast.LENGTH_LONG).show();
}
}
case REQUEST_LOCATION:
{
//check if length of grantResults is greater than 0 and equal to PERMISSION_GRANTED
if(grantResults.length>0&&grantResults[0]==PackageManager.PERMISSION_GRANTED)
{
Toast.makeText(this,"Location Permission Granted",Toast.LENGTH_LONG).show();
updateGPS();
}
else
{
Toast.makeText(this,"Location Permission Denied",Toast.LENGTH_LONG).show();
}
}
case REQUEST_CALL:
{
//check if length of grantResults is greater than 0 and equal to PERMISSION_GRANTED
if(grantResults.length>0&&grantResults[0]==PackageManager.PERMISSION_GRANTED)
{
Toast.makeText(this,"Call Permission Granted",Toast.LENGTH_LONG).show();
updateGPS();
}
else
{
Toast.makeText(this,"Call Permission Denied",Toast.LENGTH_LONG).show();
}
}
}//switch
}
private void updateGPS(){
//get permissions from the user to track GPS
//get current location
//update string
fusedLocationProviderClient = LocationServices.getFusedLocationProviderClient(MainActivity.this);
if(ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION)== PackageManager.PERMISSION_GRANTED){
//user gave the permissions
fusedLocationProviderClient.getLastLocation().addOnSuccessListener(this, new OnSuccessListener<Location>() {
#Override
public void onSuccess(Location location) {
//we got permissions. put the values of location.
updateLocation(location);
}
});
}
else{
if(Build.VERSION.SDK_INT>=Build.VERSION_CODES.M){
requestPermissions(new String[]{Manifest.permission.ACCESS_FINE_LOCATION},REQUEST_LOCATION);
}
}
}
private void updateLocation(Location location) {
//update the location of the person
mLatitude = String.valueOf(location.getLatitude());
mLongitude = String.valueOf(location.getLongitude());
Toast.makeText(this,"Latitude = "+mLatitude,Toast.LENGTH_SHORT).show();
Toast.makeText(this,"Longitude = "+mLongitude,Toast.LENGTH_SHORT).show();
Cursor cursor= myDB.getEveryone();
recyclerView.setAdapter(new CustomAdapter(MainActivity.this, Contact_id, Contact_Name, Contact_Number,mLatitude,mLongitude));
recyclerView.invalidate();
}
void storeDataInArrays() {
customAdapter.notifyDataSetChanged();
Contact_id.clear();
Contact_Name.clear();
Contact_Number.clear();
Cursor cursor = myDB.getEveryone();
if (cursor.getCount() == 0) {
//Add blank page
} else {
while (cursor.moveToNext()) {
Contact_id.add(cursor.getString(0));
Contact_Name.add(cursor.getString(1));
Contact_Number.add(cursor.getString(2));
}
}
recyclerView.setAdapter(new CustomAdapter(MainActivity.this, Contact_id, Contact_Name, Contact_Number,mLatitude,mLongitude));
customAdapter.notifyDataSetChanged();
}
public void removeItem(int position){
Contact_id.remove(true);
storeDataInArrays();
customAdapter.notifyDataSetChanged();
}
//public void onRequestPermissionResult(int requestCOde,String permissions[],int[] grantResults){}//method
public void onLocationChanged(Location location) {
}
public void onProviderDisabled(String provider) {
Log.d("Latitude","disable");
}
public void onProviderEnabled(String provider) {
Log.d("Latitude","enable");
}
public void onStatusChanged(String provider, int status, Bundle extras) {
Log.d("Latitude","status");
}
}
What do I seem to be doing wrong here ?
Would appreciate any and all help.
I am not really sure but updating the ArrayList(s) should do it.
mDelete.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
//int id= Integer.parseInt(Contact_id.getText.toString());
int contactId = Integer.parseInt(Contact_id_txt.getText().toString());
Toast.makeText(context, "int id ="+contactId+"Contact id ="+Contact_id, Toast.LENGTH_SHORT).show();
DatabaseHelper databaseHelper = new DatabaseHelper(context);
boolean success = databaseHelper.deleteOne(contactId);
Contact_id.remove(Integer.valueOf(contactId));
Toast.makeText(context, "Contact Deleted", Toast.LENGTH_SHORT).show();
notifyDataSetChanged();
}
Contact_Name and Contact_number might need to be updated too I think but it will depend on how the MainActivity code will deal with it.
I have a fragment with this view:
XML:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:tag="general"
android:id="#+id/root"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#343535"
android:orientation="vertical"
tools:context=".fragments.GeneralFragment">
<Button
android:id="#+id/hello"
android:layout_width="match_parent"
android:layout_height="60dp"
android:gravity="center_vertical"
android:onClick="onClick"
android:text="#string/hello" />
<Button
android:id="#+id/observed"
android:layout_width="match_parent"
android:layout_height="60dp"
android:gravity="center_vertical"
android:onClick="onClick"
android:text="#string/observed" />
<Button
android:id="#+id/thanks"
android:layout_width="match_parent"
android:layout_height="60dp"
android:gravity="center_vertical"
android:onClick="onClick"
android:text="#string/thanks" />
</LinearLayout>
There are 3 buttons. Whenever you click on one of them, its text will be displayed.
Now I would like to add another button but dynamically. It should be added before #+id/hello.
I have tried it with
LinearLayout root = (LinearLayout) view.findViewById(R.id.root);
root.addView();
but it looks completely wrong since some parameters are missing.
For instance, the new button should be like:
XML:
<Button
android:layout_width="match_parent"
android:layout_height="60dp"
android:gravity="center_vertical"
android:onClick="onClick"
android:text="I am a dynamic text" />
This button should be saved permanently in the app. How can I do this?
Update
I am using a dialog, so this is the class:
#SuppressLint("ValidFragment")
public class Dialog extends DialogFragment {
private final int _layout;
private TextInputEditText _customTextField;
#SuppressLint("ValidFragment")
public Dialog(int layout) {
_layout = layout;
}
public interface ICustomTts {
void customTts(String input, Activity activity);
}
public ICustomTts iCustomTts;
public interface ITarget {
void getTarget(String input);
}
public ITarget iTarget;
#RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, Bundle savedInstanceState) {
final View view = inflater.inflate(_layout, container, false);
// Display fragment_custom
if (_layout == R.layout.fragment_custom) {
_customTextField = view.findViewById(R.id.customTextField);
Button _customBtn = view.findViewById(R.id.customCta);
_customBtn.setOnClickListener(new View.OnClickListener() {
#RequiresApi(api = Build.VERSION_CODES.M)
#Override
public void onClick(View view) {
Log.d(TAG, "onClick: Clicked on CTA of custom");
String input = _customTextField.getText().toString();
if (!input.equals("")) {
iCustomTts.customTts(input, getActivity());
_dismiss();
}
}
});
MaterialCheckBox customeSave = view.findViewById(R.id.customSave);
customeSave.setOnClickListener(new View.OnClickListener() {
#RequiresApi(api = Build.VERSION_CODES.M)
#Override
public void onClick(View v) {
Log.d(TAG, "customeSave was clicked!");
LinearLayout root = view.findViewById(R.id.root);
Button button = new Button(getContext());
float heightInPixel = 60 * getResources().getDisplayMetrics().density;
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, (int) heightInPixel);
params.gravity = Gravity.CENTER;
button.setText("I am a dynamic text");
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// Do the stuff on the click
}
});
root.addView(button, 0);
}
});
}
// Display fragment_target
if (_layout == R.layout.fragment_target) {
_customTextField = view.findViewById(R.id.targetTextField);
Button _customBtn = view.findViewById(R.id.targetCta);
_customBtn.setOnClickListener(new View.OnClickListener() {
#RequiresApi(api = Build.VERSION_CODES.M)
#Override
public void onClick(View view) {
Log.d(TAG, "onClick: Clicked on CTA of target");
String input = _customTextField.getText().toString();
if (!input.equals("")) {
iTarget.getTarget(input);
_dismiss();
}
}
});
}
return view;
}
/**
* Dismissing the dialog
*/
private void _dismiss() {
this.dismiss();
}
#Override
public void onAttach(Context context) {
super.onAttach(context);
try {
if (_layout == R.layout.fragment_custom) {
iCustomTts = (ICustomTts) getActivity();
}
else if (_layout == R.layout.fragment_target) {
iTarget = (ITarget) getActivity();
}
}
catch (ClassCastException e) {
Log.e(TAG, "onAttach: ClassCastException: " + e.getMessage());
}
}
}
You need to use the two-argument version of addView() to determine the order (index) of the button inside the LinearLayout:
LinearLayout root = view.findViewById(R.id.root);
Button button = new Button(requireContext());
float heightInPixel = 60 * getResources().getDisplayMetrics().density;
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, (int) heightInPixel);
params.gravity = Gravity.CENTER;
button.setText("I am a dynamic text");
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// Do the stuff on the click
}
});
root.addView(button, 0);
I have ListView with a custom list layout. I am using an ArrayList and ArrayAdapter for this. I am having a difficult time removing selected items from the arraylist. I am not sure want I am doing wrong. Here's an example of a arraylist that I have:
Item A
Item B
Item C
Item D
Let's say that I selected Item C next on button clicked labeled "Remove" I want Item C removed from the list. How do I accomplish this? Currently my code only removes the item on index 0. I want selected item index to be removed.
Here's my codes...
Java Class:
public class MainActivity extends AppCompatActivity {
ListView lstVw;
Button addBtn, removeBtn, clearListBtn;
ArrayList<String> arrayList;
ArrayAdapter<String> adapter;
int getPosition = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
lstVw = findViewById(R.id.lstView);
addBtn = findViewById(R.id.add_item_btn);
removeBtn = findViewById(R.id.remove_item_btn);
clearListBtn = findViewById(R.id.clear_list_btn);
arrayList = new ArrayList<>();
adapter = new ArrayAdapter<>(getApplicationContext(), R.layout.item_list, R.id.item_tv, arrayList);
lstVw.setAdapter(adapter);
lstVw.setOnItemClickListener(new android.widget.AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
String getItem = adapter.getItem(position);
getPosition = Integer.parseInt(getItem);
}
});
addBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
final AlertDialog.Builder adb = new AlertDialog.Builder(MainActivity.this);
adb.setTitle("Enter Item Name");
final EditText itemTxt = new EditText(MainActivity.this);
itemTxt.setText(getString(R.string.default_item_name_value));
itemTxt.setInputType(InputType.TYPE_CLASS_TEXT);
adb.setView(itemTxt);
adb.setPositiveButton("Add", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
String getItem = itemTxt.getText().toString();
Set<String> s = new LinkedHashSet<>(arrayList);
if (s.contains(getItem)) {
arrayList.clear();
arrayList.addAll(s);
Toast.makeText(getApplicationContext(), getItem + " already exists in the list!", Toast.LENGTH_LONG).show();
} else {
arrayList.add(getItem);
adapter.notifyDataSetChanged();
}
}
});
adb.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
}
});
adb.create();
adb.show();
}
});
clearListBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (!arrayList.isEmpty()) {
arrayList.clear();
adapter.notifyDataSetChanged();
}
}
});
removeBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String getItem = arrayList.get(getPosition);
arrayList.remove(getItem);
adapter.notifyDataSetChanged();
Toast.makeText(getApplicationContext(), getItem + " is removed!", Toast.LENGTH_LONG).show();
}
});
}
}
Main XML:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/rl"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center">
<ScrollView
android:layout_width="match_parent"
android:layout_height="650dp">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="650dp">
<ListView
android:id="#+id/lstView"
android:layout_width="match_parent"
android:layout_height="650dp"
tools:ignore="NestedScrolling" />
</RelativeLayout>
</ScrollView>
<include layout="#layout/action_buttons"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"/>
Action Buttons XML:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="50dp"
android:layout_gravity="center|top">
<Button
android:id="#+id/add_item_btn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:textAllCaps="false"
android:text="#string/add_item_text"
android:textSize="14sp"
android:textStyle="bold"
android:textColor="#android:color/black"/>
<Button
android:id="#+id/remove_item_btn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_toEndOf="#id/add_item_btn"
android:textAllCaps="false"
android:text="Remove Item"
android:textColor="#android:color/black"
android:textSize="14sp"
android:textStyle="bold"/>
<Button
android:id="#+id/clear_list_btn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_toEndOf="#id/remove_item_btn"
android:textAllCaps="false"
android:text="#string/clear_list_text"
android:textSize="14sp"
android:textStyle="bold"
android:textColor="#android:color/black"/>
My Custom List Layout XML:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/container"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<ScrollView
android:layout_width="match_parent"
android:layout_height="wrap_content">
<TextView
android:id="#+id/item_tv"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textStyle="bold"
android:textSize="20sp"
android:textColor="#android:color/black"/>
</ScrollView>
I appreciate the help! Thanks!
removeBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String getItem = arrayList.get(getPosition);
arrayList.remove(getItem);
adapter.notifyDataSetChanged();
Toast.makeText(getApplicationContext(), getItem + " is removed!", Toast.LENGTH_LONG).show();
}
});
From where are you getting this getPosition?
It looks to me like your int getPosition = 0; variable is not getting updated with your new position. On your click listener you are trying to parse the value of your selected item to an Integer, maybe you could try simply updating with the current position instead?
lstVw.setOnItemClickListener(new android.widget.AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
getPosition = position;
}
});
Edit:
You could go with something like this:
Create an interface that your activity will implement and will be used by your adapter to notify a position change:
public interface PositionChangeListener {
void onPositionChanged(int newPosition);
}
Create a custom adapter:
public class CustomAdapterView extends BaseAdapter {
private Context context;
private PositionChangeListener listener;
private ArrayList<String> items;
public CustomAdapterView(Context context, ArrayList<String> items, PositionChangeListener listener) {
this.context = context;
this.items = items;
this.listener = listener;
}
#Override
public int getCount() {
return items.size();
}
#Override
public Object getItem(int position) {
return items.get(position);
}
#Override
public long getItemId(int position) {
return 0;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
ViewHolder viewHolder = null;
if (convertView == null) {
convertView = LayoutInflater.from(context).inflate( R.layout.item_list, null);
viewHolder = new ViewHolder();
viewHolder.txt = convertView.findViewById(R.id.item_tv);
viewHolder.txt.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
listener.onPositionChanged(position);
}
});
convertView.setTag(viewHolder);
} else {
viewHolder = (ViewHolder) convertView.getTag();
}
viewHolder.txt.setText(items.get(position));
return convertView;
}
private class ViewHolder {
TextView txt;
}
}
And now in your activity:
public class MainActivity extends AppCompatActivity implements PositionChangeListener{
ListView lstVw;
Button addBtn, removeBtn, clearListBtn;
ArrayList<String> arrayList;
BaseAdapter adapter;
int getPosition = 0;
#Override
public void onPositionChanged(int newPosition) {
getPosition = newPosition;
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
lstVw = findViewById(R.id.lstView);
addBtn = findViewById(R.id.add_item_btn);
removeBtn = findViewById(R.id.remove_item_btn);
clearListBtn = findViewById(R.id.clear_list_btn);
arrayList = new ArrayList<>();
adapter = new CustomAdapterView(this, arrayList, this);
lstVw.setAdapter(adapter);
addBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
final AlertDialog.Builder adb = new AlertDialog.Builder(MainActivity.this);
adb.setTitle("Enter Item Name");
final EditText itemTxt = new EditText(MainActivity.this);
itemTxt.setText("default item name");
itemTxt.setInputType(InputType.TYPE_CLASS_TEXT);
adb.setView(itemTxt);
adb.setPositiveButton("Add", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
String getItem = itemTxt.getText().toString();
Set<String> s = new LinkedHashSet<>(arrayList);
if (s.contains(getItem)) {
arrayList.clear();
arrayList.addAll(s);
Toast.makeText(getApplicationContext(), getItem + " already exists in the list!", Toast.LENGTH_LONG).show();
} else {
arrayList.add(getItem);
adapter.notifyDataSetChanged();
}
}
});
adb.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
}
});
adb.create();
adb.show();
}
});
clearListBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (!arrayList.isEmpty()) {
arrayList.clear();
adapter.notifyDataSetChanged();
}
}
});
removeBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String getItem = arrayList.get(getPosition);
arrayList.remove(getItem);
adapter.notifyDataSetChanged();
Toast.makeText(getApplicationContext(), getItem + " is removed!", Toast.LENGTH_LONG).show();
}
});
}
}
I want to connect to paired Bluetooth devices by clicking on them using two ListViews.
One ListView should display all paired devices, those items should be clickable and get connected due to a click on the item itsself. Then this item should be displayed in the second ListView that shows connected devices.
I had several attempts to this problem but i couldnt manage to get it working. Hope you can help.
Here is my Fragment:
EDIT:
public class MainActivityFragment extends Fragment implements OnClickListener {
Button connectButton;
BluetoothAdapter mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
private static final int ENABLE_BLUETOOTH = 1;
private static final String TAG = MainActivityFragment.class.getSimpleName();
ArrayList<String> mPairedDevicesArrayList;
ArrayAdapter<String> mPairedDevicesAdapter;
ListView listViewPaired, listViewConnected;
public void initBluetooth(){
if(!mBluetoothAdapter.isEnabled()) {
Intent intent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(intent, ENABLE_BLUETOOTH);
}
}
#Override
public void onCreate(Bundle savedInstance){
super.onCreate(savedInstance);
mPairedDevicesArrayList = new ArrayList<>();
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup parent, Bundle savedInstanceState){
View rootView = inflater.inflate(R.layout.fragment_connect, parent, false);
connectButton = (Button) rootView.findViewById(R.id.connectButton);
connectButton.setOnClickListener(this);
listViewPaired = (ListView) rootView.findViewById(R.id.listViewPaired);
listViewConnected = (ListView) rootView.findViewById(R.id.listViewConnected);
return rootView;
}
#Override
public void onClick(View rootView){
connectButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
if(mBluetoothAdapter.isEnabled()) {
if(mBluetoothAdapter.isDiscovering()){
Log.i(TAG, "cancel discovery");
mBluetoothAdapter.cancelDiscovery();
}
Log.i(TAG, "Bluetooth start search");
mBluetoothAdapter.startDiscovery();
getPairedDevices();
}
else {
Log.i(TAG, "Bluetooth not activated");
initBluetooth();
}
}
}); listViewPaired.setOnItemClickListener(new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View v, int position, long id) {
listViewConnected.setAdapter(mPairedDevicesAdapter);
}
});
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == 1) {
if (resultCode == RESULT_OK) {
Toast.makeText(getActivity().getApplicationContext(), "Bluetooth enabled", Toast.LENGTH_LONG).show();
} else if (resultCode == RESULT_CANCELED) {
Toast.makeText(getActivity().getApplicationContext(), "User canceled", Toast.LENGTH_LONG).show();
}
}
}
private void getPairedDevices() {
Set<BluetoothDevice> pairedDevice = mBluetoothAdapter.getBondedDevices();
if(pairedDevice.size()>0)
{
for(BluetoothDevice device : pairedDevice)
{
mPairedDevicesArrayList.add(device.getName()+"\n"+device.getAddress()); mPairedDevicesAdapter = new ArrayAdapter<>(getActivity().getApplicationContext(), R.layout.fragment_connect); listViewPaired.setAdapter(mPairedDevicesAdapter);
Log.i(TAG, "devices in List");
}
}
}
Here is my Fragment-XML:
<TextView
android:text="Welcome in Fragment!"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/textView"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_marginTop="36dp" />
<Button
android:text="Connect"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/textView"
android:layout_centerHorizontal="true"
android:layout_marginTop="88dp"
android:id="#+id/connectButton" />
<ListView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
tools:background="#android:color/holo_blue_bright"
android:layout_toLeftOf="#+id/connectButton"
android:layout_toStartOf="#+id/connectButton"
android:layout_below="#+id/connectButton"
android:id="#+id/listViewPaired" />
<ListView
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:background="#android:color/darker_gray"
android:layout_toRightOf="#+id/connectButton"
android:layout_toEndOf="#+id/connectButton"
android:layout_below="#+id/connectButton"
android:id="#+id/listViewConnected" />
ArrayAdapter uses a TextView to display each item within it.
See ArrayAdapter
It has a number of constructors that can be used,You can use this constructor to initialize the adapter with you data
ArrayAdapter(Context context, int resource, T[] objects).
And then set it to your listView
like this:
mPairedDevicesAdapter = new ArrayAdapter<>(getActivity().getApplicationContext(), android.R.layout.simple_list_item_1, mPairedDevicesArrayList);
listViewPaired.setAdapter(mPairedDevicesAdapter);
and to set an onClickListener for ListView rows, do that:
listViewPaired.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View v, int position, long id) {
// do you code
}
}
See more details here
I have added navigation view and drawer layout in my app. When I open and close the drawer it lags in time. opens and close slowly. I got this issue prominently on version 4.4 also on 6.0 but not as prominently as 4.4.
When I am running on 4.4 device as I open the drawer I noticed messages in log that too much work may be doing on main thread.
So I tried to comment all the code except the navigation drawer and options menu code. So after that I found it was working bit well.
Is it the issue? or some memory issue can be there? But on larger memory devices also I found the problem.
Do I need to create another activity for other code? So that drawer will work faster?
I also tried to create a fragment and replaced it in framelayout of main activity to separate the code. But it was still lagging.
If I create new activity still I need all the navigation code in that activity, it will be again a same thing.
I am not getting what can be the issue. Can anyone please help.. Thank you..
Here is code:
public class MainActivity extends AppCompatActivity implements GetContactsAsyncTask.ContactGetCallBack,UpdateUserAsyncTask.UpdateUserCallBack {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
contactDb = new ContactTableHelper(MainActivity.this);
mDb = new UserTableHelper(MainActivity.this);
boolean result = Utility.checkAndRequestPermissions(MainActivity.this);
LocalBroadcastManager.getInstance(this).registerReceiver(mRegistrationBroadcastReceiver,
new IntentFilter(REGISTRATION_COMPLETE));
LocalBroadcastManager.getInstance(this).registerReceiver(mRegistrationBroadcastReceiver,
new IntentFilter(PUSH_NOTIFICATION));
NotificationUtils.clearNotifications(getApplicationContext());
sharedpreferences = getSharedPreferences("UserProfile", Context.MODE_PRIVATE);
mUserId = sharedpreferences.getString("userId", "");
firstTimeLogin = sharedpreferences.getBoolean("login", false);
refreshedToken = sharedpreferences.getString("deviceId", "");
parentLayout = (LinearLayout) findViewById(R.id.toolbar_container);
setupView();
mUser = new User();
url = sharedpreferences.getString("url", "");
contactList = new ArrayList<Contact>();
txtuserName = (TextView) findViewById(R.id.txtusername);
txtmobile = (TextView) findViewById(R.id.txtmobile);
profileImageView = (CircleImageView) findViewById(R.id.thumbnail);
if (profileImageView != null) {
profileImageView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
drawerLayout.closeDrawers();
Intent Intent = new Intent(MainActivity.this, ProfileActivity.class);
Intent.putExtra("user", mUser);
Intent.putExtra("url", url);
startActivity(Intent);
}
});
}
BitmapFactory.Options bmOptions = new BitmapFactory.Options();
Bitmap bitmap = BitmapFactory.decodeFile(image.getPath(), bmOptions);
if (bitmap != null) {
profileImageView.setImageBitmap(bitmap);
} else {
profileImageView.setImageDrawable(ContextCompat.getDrawable(MainActivity.this, R.drawable.ic_account_circle_white_48dp));
}
ImageView sync = (ImageView) findViewById(R.id.sync);
sync.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
contactList.clear();
contactDb.deleteAllContacts();
GetContactsAsyncTask getContactsAsyncTask = new GetContactsAsyncTask(MainActivity.this, MainActivity.this, mUserId, MainActivity.this);
getContactsAsyncTask.execute(mUserId);
}
});
}
void setupView() {
File sd = Environment.getExternalStorageDirectory();
image = new File(sd + "/Profile", "Profile_Image.png");
drawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
navigationView = (NavigationView) findViewById(R.id.navigation_view);
navigationView.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(MenuItem menuItem) {
drawerLayout.closeDrawers();
menuItem.setChecked(true);
FragmentManager fragmentManager = getSupportFragmentManager();
switch (menuItem.getItemId()) {
case R.id.nav_menu_contacts:
fragmentManager.beginTransaction().replace(R.id.container, fragment).commit();
break;
case R.id.nav_menu_settings:
Intent i = new Intent(MainActivity.this, PreferencesActivity.class);
i.addFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION);
startActivity(i);
break;
case R.id.nav_log_out:
SharedPreferences pref = getSharedPreferences("UserProfile", MODE_PRIVATE);
SharedPreferences.Editor editor = pref.edit();
editor.remove("UserUsername");
editor.remove("userId");
editor.remove("url");
editor.remove("login");
editor.remove("company");
editor.remove("emailId");
editor.remove("profileImage");
editor.remove("fullName");
editor.remove("homeAddress");
editor.remove("workAddress");
editor.remove("workPhone");
editor.remove("pass");
editor.remove("jobTitle");
editor.remove("mobileNo");
editor.commit();
mDb.deleteAllUsers();
contactDb.deleteAllContacts();
UpdateTokenAsyncTask updateTokenAsyncTask = new UpdateTokenAsyncTask(MainActivity.this, mUserId, "");
updateTokenAsyncTask.execute(mUserId, "");
finish();
i = new Intent(MainActivity.this, LoginActivity.class);
i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);
i.addFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION);
startActivity(i);
break;
case R.id.nav_invite:
i = new Intent(MainActivity.this, InviteContactsActivity.class);
i.addFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION);
startActivity(i);
break;
}
return true;
}
});
Toolbar toolbar = (Toolbar) findViewById(R.id.main_toolbar);
TextView mTitle = (TextView) findViewById(R.id.toolbar_title);
final ImageView menu = (ImageView) findViewById(R.id.menu);
menu.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
PopupMenu popup = new PopupMenu(MainActivity.this, menu);
popup.getMenuInflater().inflate(R.menu.main_pop_up_menu, popup.getMenu());
popup.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {
public boolean onMenuItemClick(MenuItem item) {
if (item.getItemId() == R.id.pendingInvites) {
startActivity(new Intent(MainActivity.this, PendingInvitesActivity.class));
} else if (item.getItemId() == R.id.feedback) {
final MaterialDialog dialog = new MaterialDialog.Builder(MainActivity.this)
.title("Feedback")
.customView(R.layout.feedback_dialog, true).build();
positiveAction = dialog.getActionButton(DialogAction.POSITIVE);
edtName = (EditText) dialog.getCustomView().findViewById(R.id.editName);
edtEmailId = (EditText) dialog.getCustomView().findViewById(R.id.editTextEmailId);
edtComment = (EditText) dialog.getCustomView().findViewById(R.id.editTextComment);
buttonSave = (Button) dialog.getCustomView().findViewById(R.id.buttonSave);
buttonSave.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
View view1 = getCurrentFocus();
if (view1 != null) {
InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(view1.getWindowToken(), 0);
}
mName = String.valueOf(edtName.getText().toString());
mEmailId = String.valueOf(edtEmailId.getText().toString());
mComment = String.valueOf(edtComment.getText().toString());
if (mComment.equals("")) {
showAlert("Please enter comments.");
} else if (mEmailId.equals("")) {
showAlert("Please enter an email-id.");
} else {
if (!isValidEmail(mEmailId)) {
showAlert("Please enter valid email id.");
} else {
HashMap<String, String> params = new HashMap<String, String>();
params.put("name", mName);
params.put("email_id", mEmailId);
params.put("comment", mComment);
CreateFeedbackAsyncTask createFeedbackAsyncTask = new CreateFeedbackAsyncTask(MainActivity.this, MainActivity.this);
createFeedbackAsyncTask.execute(params);
dialog.dismiss();
}
}
}
});
edtName.addTextChangedListener(new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
positiveAction.setEnabled(s.toString().trim().length() > 0);
}
#Override
public void afterTextChanged(Editable s) {
View view = getCurrentFocus();
if (view != null) {
InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(view.getWindowToken(), 0);
}
}
});
edtComment.addTextChangedListener(new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
positiveAction.setEnabled(s.toString().trim().length() > 0);
View view = getCurrentFocus();
if (view != null) {
InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(view.getWindowToken(), 0);
}
}
#Override
public void afterTextChanged(Editable s) {
}
});
edtEmailId.addTextChangedListener(new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
positiveAction.setEnabled(s.toString().trim().length() > 0);
View view = getCurrentFocus();
if (view != null) {
InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(view.getWindowToken(), 0);
}
}
#Override
public void afterTextChanged(Editable s) {
}
});
dialog.show();
positiveAction.setEnabled(false);
return true;
}
return true;
}
});
popup.show();//showing popup menu
}
});
if (toolbar != null) {
toolbar.setTitle("");
setSupportActionBar(toolbar);
}
if (toolbar != null) {
toolbar.setNavigationIcon(R.drawable.ic_menu_white_24dp);
toolbar.setNavigationOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
drawerLayout.openDrawer(GravityCompat.START);
}
});
}
}
#Override
public void doPostExecute(JSONArray response) throws JSONException {
contactListArray = response;
contactDb = new ContactTableHelper(MainActivity.this);
if (null == contactList) {
contactList = new ArrayList<Contact>();
}
for (int i = 0; i < contactListArray.length(); i++) {
JSONObject subObject1 = contactListArray.getJSONObject(i);
Contact contact = new Contact();
JSONObject subObject = subObject1;
String contactName = subObject.getString("user_name");
//name of the attribute in response
String pass = subObject.getString("password");
String contactId = subObject.getString("user_id");
String contactMobile = subObject.getString("mobile_no");
String contactEmailId = subObject.getString("email_id");
String contactProfile = subObject.getString("profile_image");
String fullName = subObject.getString("full_name");
String jobTitle = subObject.getString("job_title");
String homeAddress = subObject.getString("home_address");
String workPhone = subObject.getString("work_phone");
String workAddress = subObject.getString("work_address");
String company = subObject.getString("company");
contact.setmThumbnail(contactProfile);
contact.setmUserName(contactName);
contact.setmMobileNo(contactMobile);
contact.setmEmailId(contactEmailId);
contact.setmProfileImage(contactProfile);
contact.setContactId(contactId);
contact.setmHomeAddress(homeAddress);
contact.setmFullName(fullName);
contact.setmJobTitle(jobTitle);
contact.setmWorkAddress(workAddress);
contact.setmWorkPhone(workPhone);
contact.setmPass(pass);
contact.setmCompany(company);
contactList.add(contact);//adding string to arraylist
contactDb.addContact(new Contact(contactId, contactName, pass, contactMobile, contactEmailId, contactProfile, fullName, jobTitle, workAddress, workPhone, homeAddress, company));
}
adapter = new ContactAdapter(MainActivity.this, contactList);
recyclerView.setAdapter(adapter);
recyclerView.setHasFixedSize(true);
recyclerView.setItemViewCacheSize(20);
recyclerView.setDrawingCacheEnabled(true);
recyclerView.setDrawingCacheQuality(View.DRAWING_CACHE_QUALITY_HIGH);
}
#Override
public void onResume() {
super.onResume();
contactList.clear();
if (!firstTimeLogin) {
contactList.clear();
contactList = contactDb.getAllContacts();
mUser = mDb.getUser(mUserId);
txtuserName.setText(mUser.getmUserName());
txtmobile.setText(mUser.getmMobileNo());
} else {
new GetUserAsyncTask1(MainActivity.this,mUserId).execute(mUserId);
new GetContactsAsyncTask(this, MainActivity.this, mUserId, MainActivity.this).execute();
firstTimeLogin = false;
SharedPreferences.Editor editor = getSharedPreferences("UserProfile", MODE_PRIVATE).edit();
editor.putBoolean("login", firstTimeLogin);
editor.commit();
}
recyclerView = (RecyclerView) findViewById(R.id.recycler_view);
recyclerView.setHasFixedSize(true);
RecyclerView.LayoutManager mLayoutManager = new LinearLayoutManager(MainActivity.this);
recyclerView.setLayoutManager(mLayoutManager);
recyclerView.addItemDecoration(new DividerItemDecoration(this, LinearLayoutManager.VERTICAL));
recyclerView.setItemAnimator(new DefaultItemAnimator());
adapter = new ContactAdapter(MainActivity.this, contactList);
recyclerView.setAdapter(adapter);
recyclerView.addOnItemTouchListener(new RecyclerTouchListener(MainActivity.this, recyclerView, new ClickListener() {
#Override
public void onClick(View view, int position) {
final Contact contact = contactList.get(position);
}
#Override
public void onLongClick(View view, int position) {
}
}));
}
#Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
switch (requestCode) {
case REQUEST_ID_MULTIPLE_PERMISSIONS: {
Map<String, Integer> perms = new HashMap<String, Integer>();
perms.put(Manifest.permission.WRITE_EXTERNAL_STORAGE, PackageManager.PERMISSION_GRANTED);
perms.put(Manifest.permission.CAMERA, PackageManager.PERMISSION_GRANTED);
perms.put(Manifest.permission.READ_CONTACTS, PackageManager.PERMISSION_GRANTED);
perms.put(Manifest.permission.SEND_SMS, PackageManager.PERMISSION_GRANTED);
for (int i = 0; i < permissions.length; i++)
perms.put(permissions[i], grantResults[i]);
if (perms.get(Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED
&& perms.get(Manifest.permission.READ_CONTACTS) == PackageManager.PERMISSION_GRANTED
&& perms.get(Manifest.permission.SEND_SMS) == PackageManager.PERMISSION_GRANTED
&& perms.get(Manifest.permission.CAMERA) == PackageManager.PERMISSION_GRANTED) {
} else {
showAlert("Some Permissions are Denied.");
}
}
break;
default:
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
}
}
#Override
public void doPostExecute(JSONObject response, Boolean update) throws JSONException {
}
}
Main layout :
<android.support.v4.widget.DrawerLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="#+id/drawer_layout"
android:layout_width="match_parent"
android:layout_height="match_parent">
<FrameLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/container">
</FrameLayout>
<!-- Your normal content view -->
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:id = "#+id/toolbar_container">
<!-- We use a Toolbar so that our drawer can be displayed
in front of the action bar -->
<android.support.v7.widget.Toolbar xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="#+id/main_toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:background="?attr/colorPrimary"
android:theme="#style/ThemeOverlay.AppCompat.Dark.ActionBar"
app:popupTheme="#style/ThemeOverlay.AppCompat.Light">
<RelativeLayout
android:layout_width="fill_parent"
android:layout_height="match_parent">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="#string/Contacts"
android:layout_gravity="center"
android:id="#+id/toolbar_title"
android:textSize="20sp"
android:textColor="#ffffff"
android:textStyle="bold"
android:textAlignment="center"
android:gravity="center_vertical|center|center_horizontal"
android:layout_toLeftOf="#+id/sync"
android:layout_toStartOf="#+id/sync"
android:layout_centerInParent="true"
android:layout_marginLeft="30dp"
android:layout_marginRight="10dp" />
<ImageView
android:layout_width="24dp"
android:layout_height="24dp"
android:background="#drawable/ic_refresh_white_24dp"
android:id="#+id/sync"
android:layout_gravity = "right"
android:layout_toStartOf="#+id/menu"
android:layout_toLeftOf="#+id/menu"
android:layout_centerVertical="true"
android:layout_alignParentRight="false"
android:layout_marginRight="10dp" />
<ImageView
android:layout_width="24dp"
android:layout_height="24dp"
android:layout_gravity= "end"
android:layout_marginRight="10dp"
android:background="#drawable/ic_more_vert_white_36dp"
android:id="#+id/menu"
android:layout_alignParentEnd="true"
android:layout_centerVertical="true"
android:layout_alignParentRight="true" />
</RelativeLayout>
</android.support.v7.widget.Toolbar>
<view
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#ffffff"
class="android.support.v7.widget.RecyclerView"
android:id="#+id/recycler_view"
android:layout_alignParentStart="true"
android:layout_alignParentLeft="true" />
<!-- The rest of your content view -->
</LinearLayout>
<android.support.design.widget.NavigationView
android:id="#+id/navigation_view"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_gravity="start"
android:background="?attr/colorPrimary"
app:headerLayout="#layout/drawer_header"
app:itemTextColor="#color/yourColor"
app:itemIconTint="#color/yourColor"
app:menu="#menu/nav_menu" >
<LinearLayout
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<include
layout="#layout/drawer_header"
android:layout_width="match_parent"
android:layout_height="103dp" />
<ExpandableListView
android:id="#+id/elvGuideNavigation"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:groupIndicator="#null"
/>
</LinearLayout>
</android.support.design.widget.NavigationView>
Do the Json Parsing and adding the Entries into the DB also in Background Thread and Pass only the ArrayList of Entries to the Main Thread, this way you can reduce the Load on the Main Thread.
Another thing you can try is Enabling hardwareAcceleration to true
Definitely try to move any database operations on another threads. Decoding that bitmap in onCreate() also is dangerous.
Maybe organising your code will help a bit.