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);
Related
I am working on a ANDROID project and in it I have multiple buttons.
REQUIREMENT:-
1.When I click on a button once I want it to change to green color and when I click on same button again I want it to change back to original color.
2.When a button is selected(i.e. color becomes GREEN) I want to add a number to a array list and when I select it once again I want to remove the added number from the list.
I have come up with this solution as of now. But it doesn't work.
int flag=1;
button1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
flag+=1;
if(flag%2==0) {
SeatArrayList.remove(Integer.valueOf(1));
button1.setBackgroundColor(Color.GREEN);
}
else{
SeatArrayList.add(1);
button1.setBackgroundColor(bg_yellow);
}
}
});
button3.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
flag+=1;
if(flag%2==0) {
SeatArrayList.remove(Integer.valueOf(3));
button3.setBackgroundColor(Color.GREEN);
}
else{
SeatArrayList.add(3);
button3.setBackgroundColor(bg_yellow);
}
}
});
button4.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
flag+=1;
if(flag%2==0) {
SeatArrayList.remove(Integer.valueOf(4));
button4.setBackgroundColor(Color.GREEN);
}
else{
SeatArrayList.add(4);
button4.setBackgroundColor(bg_yellow);
}
}
});
You can easily manage this by using the boolean flag, here is one example for the same!
boolean isGreen = false;
button1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if(isGreen){
isGreen = false
SeatArrayList.removeAt(SeatArrayList.size-1)
button1.setBackgroundColor(Color.YELLOW);
}else{
isGreen = true
SeatArrayList.add(1);
button1.setBackgroundColor(Color.GREEN);
}
}
});
You should create a flag for each button. I think that the following code does what you mention in the requirements:
1. XML File:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 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:orientation="vertical"
tools:context=".MainActivity">
<Button
android:id="#+id/btn1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:backgroundTint="#android:color/black"
android:text="Button 1">
</Button>
<Button
android:id="#+id/btn2"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:backgroundTint="#android:color/black"
android:text="Button 2">
</Button>
<Button
android:id="#+id/btn3"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:backgroundTint="#android:color/black"
android:text="Button 3">
</Button>
<TextView
android:id="#+id/txtNumbers"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center"
android:text="{ }"
android:textSize="18sp">
</TextView>
</LinearLayout>
2. MainActivity Java File:
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
private Button btn1, btn2, btn3;
private TextView txtNumbers;
private ArrayList<Integer> list;
private ArrayList<Boolean> isGreen;
private int initialColor;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btn1 = (Button) findViewById(R.id.btn1);
btn2 = (Button) findViewById(R.id.btn2);
btn3 = (Button) findViewById(R.id.btn3);
txtNumbers = (TextView) findViewById(R.id.txtNumbers);
btn1.setOnClickListener(this);
btn2.setOnClickListener(this);
btn3.setOnClickListener(this);
list = new ArrayList<>();
isGreen = new ArrayList<>(Collections.nCopies(3, false));//Initialize values to false (In this case for only 3 buttons)
initialColor = Color.BLACK;//The same color as in the XML file
}
#Override
public void onClick(View view) {
switch (view.getId()) {
case R.id.btn1:
requirement(btn1, 0, 0);
break;
case R.id.btn2:
requirement(btn2, 1, 1);
break;
case R.id.btn3:
requirement(btn3, 2, 2);
break;
}
}
private void requirement(Button btn, int index, int number) {
if (!isGreen.get(index)) {
btn.setBackgroundColor(Color.GREEN);
list.add(number);
printList();
isGreen.set(index, true);
} else {
btn.setBackgroundColor(initialColor);
list.remove((Integer) number);//Cast to Integer, because this will eliminate the number by its value, not index
printList();
isGreen.set(index, false);
}
}
private void printList() {
String numbers = "{ ";
for (int index = 0; index < list.size(); index++) {
numbers += list.get(index) + ", ";
}
numbers += " }";
txtNumbers.setText(numbers);
}
}
Result:
I hope it will be useful to you. I stay tuned, regards 😁/.
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;
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 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.
I want to display pie-chart in a fragment dialog box..
This is the code:--
MainActivity.java
public class MainActivity extends Activity implements
MyDialogFragment.Communicator {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
#SuppressLint("NewApi")
public void showDialog(View view) {
FragmentManager manager = getFragmentManager();
MyDialogFragment1 mydialog = new MyDialogFragment1();
mydialog.show(manager, "mydialog");
}
#Override
public void message(String data) {
Toast.makeText(getApplicationContext(), data + " button clicked",
Toast.LENGTH_SHORT).show();
}
}
and the MyDialogFragment1.java
#SuppressLint({ "NewApi", "InflateParams" })
public class MyDialogFragment1 extends DialogFragment implements OnClickListener {
Button no_button;
Context context;
private static int[] COLORS = new int[] { Color.MAGENTA, Color.CYAN };
private static String[] NAME_LIST = new String[] { "A", "B" };
private CategorySeries mSeries = new CategorySeries("");
private DefaultRenderer mRenderer = new DefaultRenderer();
private GraphicalView mChartView;
private int[] VALUES = { 40, 60 };
Communicator communicator;
#SuppressLint("NewApi")
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
if (activity instanceof Communicator) {
communicator = (Communicator) getActivity();
} else {
throw new ClassCastException(activity.toString()
+ " must implemenet MyListFragment.communicator");
}
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
setCancelable(false);
getDialog().setTitle("Title");
// View view = inflater.inflate(R.layout.main, null, false);
View view = (LinearLayout) inflater.inflate(R.layout.main,container, false);
mRenderer.setApplyBackgroundColor(true);
mRenderer.setBackgroundColor(Color.argb(100, 50, 50, 50));
mRenderer.setChartTitleTextSize(20);
mRenderer.setLabelsTextSize(15);
mRenderer.setLegendTextSize(15);
mRenderer.setMargins(new int[] { 20, 30, 15, 0 });
mRenderer.setZoomButtonsVisible(true);
mRenderer.setStartAngle(90);
for (int i = 0; i < VALUES.length; i++) {
//mSeries.add(NAME_LIST[i] + " " + VALUES[i], VALUES[i]);
mSeries.add(NAME_LIST[i] + "(" + VALUES[i]+"%)", VALUES[i]);
SimpleSeriesRenderer renderer = new SimpleSeriesRenderer();
renderer.setColor(COLORS[(mSeries.getItemCount() - 1) % COLORS.length]);
mRenderer.addSeriesRenderer(renderer);
}
if (mChartView != null) {
mChartView.repaint();
}
//yes_button = (Button) view.findViewById(R.id.yesbtn);
no_button = (Button) view.findViewById(R.id.nobtn);
// setting onclick listener for buttons
// yes_button.setOnClickListener(this);
no_button.setOnClickListener(this);
return view;
}
#SuppressLint("ShowToast")
#Override
public void onResume() {
super.onResume();
if (mChartView == null) {
LinearLayout layout = (LinearLayout) findViewById(R.id.chart);
mChartView = ChartFactory.getPieChartView(context, mSeries, mRenderer ) ;
mRenderer.setClickEnabled(true);
mRenderer.setSelectableBuffer(10);
mChartView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
SeriesSelection seriesSelection = mChartView.getCurrentSeriesAndPoint();
}
});
mChartView.setOnLongClickListener(new View.OnLongClickListener() {
#SuppressLint("ShowToast")
#Override
public boolean onLongClick(View v) {
SeriesSelection seriesSelection = mChartView.getCurrentSeriesAndPoint();
return false;
}
});
layout.addView(mChartView, new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT));
}
else {
mChartView.repaint();
}
}
private LinearLayout findViewById(int chart) {
// TODO Auto-generated method stub
return null;
}
#Override
public void onClick(View view) {
switch (view.getId()) {
case R.id.nobtn :
dismiss();
communicator.message("Dialog No btn clicked");
break;
}
}
public interface Communicator {
public void message(String data);
}
}
and the xml files are:--
activity_main.xml
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:padding="20dp" >
<Button
android:id="#+id/button1"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:onClick="showDialog"
android:text="Show Dialog" />
</LinearLayout>
and main.xml is :--
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<LinearLayout
android:id="#+id/chart"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_weight="1"
android:orientation="horizontal" >
</LinearLayout>
<Button
android:id="#+id/nobtn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBaseline="#+id/yesbtn"
android:layout_alignBottom="#+id/yesbtn"
android:layout_alignRight="#+id/textView1"
android:layout_marginRight="38dp"
android:text="No" />
</LinearLayout>
Now, When I run this program it shows the button,when I click the button it stops...
and showing the following error:--
FATAL EXCEPTION: main
Process: com.emple.dialog_android_example, PID: 21181
java.lang.ClassCastException: com.emple.dialog_android_example.MainActivity#41ef95b0 must implemenet MyListFragment.communicator
at com.emple.dialog_android_example.MyDialogFragment1.onAttach(MyDialogFragment1.java:64)
at android.app.FragmentManagerImpl.moveToState(FragmentManager.java:849)
at android.app.FragmentManagerImpl.moveToState(FragmentManager.java:1062)
at android.app.BackStackRecord.run(BackStackRecord.java:698)
at android.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:1447)
at android.app.FragmentManagerImpl$1.run(FragmentManager.java:443)
at android.os.Handler.handleCallback(Handler.java:808)
at android.os.Handler.dispatchMessage(Handler.java:103)
at android.os.Looper.loop(Looper.java:193)
at android.app.ActivityThread.main(ActivityThread.java:5324)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:515)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:824)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:640)
at dalvik.system.NativeStart.main(Native Method)
where is the problem????
I think your activity is not a instance of Communicator
Check here :
#SuppressLint("NewApi")
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
if (activity instanceof Communicator) {
communicator = (Communicator) getActivity();
} else {
throw new ClassCastException(activity.toString()
+ " must implemenet MyListFragment.communicator");
}
}