Add 2 Button ListView with Custom Adapter - java

i'm having problems trying to add 2 buttons into my listview, i'm uploading a picture with what i have and what i want
So, i just want to add those 2 buttons there, but i've been trying to do it using custom adapters but i still can't do it, if anyone could help me i would really appreciate it.
My files so far:
activity_vendor_main.xml
<?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:id="#+id/activity_vendedor_main"
android:orientation="vertical"
android:layout_width="match_parent"
android:background="#color/colorPrimary"
android:layout_height="match_parent"
android:weightSum="1">
<ImageView
android:src="#drawable/logo"
android:layout_width="209dp"
android:layout_height="106dp"
android:layout_marginBottom="20dp"
android:layout_gravity="center_horizontal" />
/>
<ImageView
android:src="#drawable/orderid1"
android:layout_width="134dp"
android:layout_height="34dp"
android:layout_gravity="center_horizontal"
/>
<SearchView
android:layout_width="match_parent"
android:layout_height="30dp"
android:id="#+id/seacrhBar"
android:textColor="#color/colorVendor"
android:layout_marginTop="25dp"
android:background="#drawable/vendor_bars_background"/>
<android.support.v7.widget.AppCompatButton
android:text="AGREGAR ORDEN"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:layout_marginTop="5dp"
android:layout_marginBottom="8dp"
android:textStyle="bold"
android:textColor="#color/colorVendor"
android:background="#drawable/single_button"
android:id="#+id/add_order1"
android:onClick="EVENTO" />
<ListView
android:layout_width="wrap_content"
android:layout_height="190dp"
android:id="#+id/tablaPedidos"
android:choiceMode="singleChoice"
android:layout_above="#+id/editText2"
android:background="#drawable/vendor_bars_background"
android:layout_weight="0.13" />
<android.support.v7.widget.AppCompatButton
android:text="CERRAR SESIÓN"
android:layout_width="120sp"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:layout_marginTop="10dp"
android:layout_marginBottom="135dp"
android:textStyle="bold"
android:textColor="#color/colorVendor"
android:background="#drawable/button_login_form"
android:id="#+id/signOut2_order_form"
android:onClick="logout" />
</LinearLayout>
MainActivity.java
public class LoginActivity extends AppCompatActivity {
GlobalClass appContext;
#BindView(R.id.input_username)
EditText _usernameText;
#BindView(R.id.input_password)
EditText _passwordText;
#BindView(R.id.btn_login)
Button _loginButton;
ProgressDialog progressDialog;
//Invocación de servicio para acceso al API
UsersHandler client = ServiceGenerator.createService(UsersHandler.class);
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
if (android.os.Build.VERSION.SDK_INT > 9) {
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
}
ButterKnife.bind(this);
appContext = (GlobalClass)getApplicationContext();
_loginButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
login();
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.menu_main, menu);
return super.onCreateOptionsMenu(menu);
}
#Override
public void onBackPressed() {
moveTaskToBack(false);
}
public void onLoginSuccess() {
_loginButton.setEnabled(true);
finish();
}
public void onLoginFailed(String message) {
Toast.makeText(getBaseContext(), message, Toast.LENGTH_LONG).show();
_loginButton.setEnabled(true);
}
public void login() {
if (!validate()) {
// onLoginFailed("Login failed");
return;
}
_loginButton.setEnabled(false);
progressDialog = new ProgressDialog(LoginActivity.this,R.style.AppTheme_Dark_Dialog);
progressDialog.setIndeterminate(true);
progressDialog.setMessage("Autenticando...");
progressDialog.show();
new android.os.Handler().postDelayed(
new Runnable() {
public void run() {
onLoginSuccess();
//progressDialog.dismiss();
}
}, 3000);
progressDialog.dismiss();
String userType = appContext.getSessionUserType();
loadUserView(userType);
}
public boolean validate() {
boolean valid = true;
String username = _usernameText.getText().toString().trim();
String password = _passwordText.getText().toString();
//if (email.isEmpty() || !android.util.Patterns.EMAIL_ADDRESS.matcher(username).matches()) {
if (username.isEmpty()) {
_usernameText.setError("Ingrese un usuario válido.");
valid = false;
} else {
_usernameText.setError(null);
}
if (password.isEmpty() || password.length() < 4) {
_passwordText.setError("No menos de 4 caracteres alfanuméricos");
valid = false;
} else {
_passwordText.setError(null);
}
if (valid) {
valid = validateApi(1, username, password);
}
return valid;
}
public boolean validateApi(int i, String username, String password) {
appContext.setSessionToken("1");
appContext.setSessionUserType(Constants.COURIER);
if (username.equals("v"))
appContext.setSessionUserType(Constants.VENDOR);
appContext.setSessionUsername("tester");
appContext.setSessionCompany("test");
appContext.saveSessionAttributes();
return true;
}
public boolean validateApi(String username, String password) {
boolean valid = false;
//Creación de request
UserLoginRequest requestObj = new UserLoginRequest(username, password);
//Declaración de request
Call<ResponseBody> call = client.userLogin(requestObj);
JSONObject json = null;
try {
ResponseBody responseBody = call.execute().body();
json = UtilsController.getJsonResponse(responseBody);
boolean success = UtilsController.isJsonValid(json);
String error = UtilsController.extractMessage(json);
if (success) {
User response = (User) UtilsController.extractDataJson(json, User.class);
appContext.setSessionToken(response.getToken());
appContext.setSessionUserType(response.getUserType());
appContext.setSessionUsername(response.getUsername());
appContext.setSessionCompany(response.getCompanyName());
appContext.saveSessionAttributes();
valid = true;
} else {
onLoginFailed(error);
return false;
}
} catch (IOException e) {
//Error en lectura de respuesta de servidor
onLoginFailed("Error interno. Intente más tarde");
} catch (JSONException e) {
//Error en campos de respuesta
onLoginFailed("Error interno. Intente más tarde");
} catch (Exception e) {
//Error general
if (json == null) {
onLoginFailed("Error interno. Intente más tarde");
}
onLoginFailed("Login failed");
}
return valid;
}
public void loadUserView(String userType) {
if (userType != null && Constants.VENDOR.equals(userType)) {
Intent userView = new Intent(this, VendorMain.class);
startActivity(userView);
} else if (Constants.COURIER.equals(userType)) {
Intent userView = new Intent(this, CourierMain.class);
startActivity(userView);
}
}
}
row_item.xml (Picture Below)
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:padding="10dp">
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true">
</LinearLayout>
<Button
android:text="EDITAR"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true"
android:id="#+id/cancel_btn" />
<Button
android:text="Cancelar"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/edit_btn"
android:layout_alignParentTop="true"
android:layout_toLeftOf="#+id/cancel_btn"
android:layout_toStartOf="#+id/cancel_btn"
android:layout_marginRight="7dp"
android:layout_marginEnd="7dp" />
<TextView
android:id="#+id/orden_title_text"
android:textStyle="bold"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="ORDEN #"
android:textAppearance="?android:attr/textAppearanceSmall"
android:textColor="#android:color/black"
android:layout_alignBaseline="#+id/edit_btn"
android:layout_alignBottom="#+id/edit_btn"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true" />
<TextView
android:id="#+id/textbox1"
android:layout_width="50dp"
android:layout_height="wrap_content"
android:layout_marginLeft="7dp"
android:text=" "
android:textAppearance="?android:attr/textAppearanceSmall"
android:textColor="#android:color/black"
android:layout_alignBaseline="#+id/orden_title_text"
android:layout_alignBottom="#+id/orden_title_text"
android:layout_toRightOf="#+id/orden_title_text"
android:layout_marginStart="7dp" />
</RelativeLayout>
row_item.xml "What i have so far"
If another files is needed in order to help me, let me know and i'll upload it.
Thanks you so much guys.

create a class like
public class TestAdapter extends BaseAdapter {
Context context;
public TestAdapter(Context context)
{
this.context=context;
}
//count of number of items in listview may be depending on the array ua passing....here i am keeping 5 it may be according to you!
int count=5;
#Override
public int getCount() {
return 5;
}
#Override
public Object getItem(int position) {
return null;
}
#Override
public long getItemId(int position) {
return 0;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
convertView= LayoutInflater.from(context).inflate(R.layout.row_item,parent,false);
TextView ordentitle=(TextView)convertView.findViewById(R.id.orden_title_text);
TextView textbox1=(TextView)convertView.findViewById(R.id.textbox1);
ordentitle.setText("Whatever yout text is");
textbox1.setText("whatever your text is");
Button editar=(Button)convertView.findViewById(R.id.edit_btn);
Button cancel=(Button)convertView.findViewById(R.id.cancel_btn);
editar.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//funtionality of edit button
}
});
cancel.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//functionality of cancel button
}
});
return convertView;
}
}
and then set this adapter to your listview in activity or fragment like this:
TestAdapter testAdapter=new TestAdapter(YourActivity.this)
yourlistview.setAdapter(testAdapter);
one more pointer :
YOU GAVE EDIT BUTTON id as cancel_btn and CANCEL BUTTON id as edit_btn!

You could create a new class that extends BaseAdapter and in the getView method you do w/e you want with the buttons. In the the activity with the listView you use the setAdapter.

Related

ViewPager inside Dialog not showing

I have a custom dialog that has a ViewPager inside of it, when the dialog shows the ViewPager is just blank, not progressing on swipe or when pressing the "Next" button I implemented. I tried slightly altering my code and it didn't work. I saw several posts like this, but none of their solutions worked. PS if some things don't make sense or have mismatched names then that's because I renamed/removed some of the files/variables to simplify.
SliderAdapter:
public class SliderAdapter extends PagerAdapter {
private Context context;
private LayoutInflater layoutInflater;
private ArrayList<String> text;
public SliderAdapter(Context context, ArrayList<String> text) {
this.context = context;
this.text = text;
}
public String[] txtH = {
"test1",
"test2",
"test3"
};
#Override
public int getCount() {
return txtH.length;
}
#Override
public boolean isViewFromObject(#NonNull View view, #NonNull Object object) {
return view == (ConstraintLayout) object;
}
#NonNull
#Override
public Object instantiateItem(#NonNull ViewGroup container, int position) {
layoutInflater = (LayoutInflater) context.getSystemService(context.LAYOUT_INFLATER_SERVICE);
View view = layoutInflater.inflate(R.layout.slide_layout_wr, container, false);
TextView txt1 = view.findViewById(R.id.txt11);
TextView txt2 = view.findViewById(R.id.txt22);
txt1.setText(txtH[position]);
txt2.setText(text.get(position));
container.addView(view);
return view;
}
#Override
public void destroyItem(#NonNull ViewGroup container, int position, #NonNull Object object) {
container.removeView((ConstraintLayout) object);
}
}
Dialog itself:
public class DialogWeeklyReport extends AppCompatDialogFragment {
...
#NonNull
#Override
public Dialog onCreateDialog(#Nullable Bundle savedInstanceState) {
final AlertDialog.Builder builder = new AlertDialog.Builder(getActivity(),
R.style.Dialog);
LayoutInflater inflater = getActivity().getLayoutInflater();
View view = inflater.inflate(R.layout.dialog, null);
preferences = getActivity().getSharedPreferences("label", 0);
Random random = new Random();
text.add("test1");
text.add("test2");
text.add("test3");
viewPager = view.findViewById(R.id.viewPager);
dotLayout = view.findViewById(R.id.dotLayout);
next = view.findViewById(R.id.next);
next.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (next.getText().toString().equals("Proceed")) {
dismiss();
} else {
viewPager.setCurrentItem(currentPage + 1);
}
}
});
back = view.findViewById(R.id.back);
next.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
viewPager.setCurrentItem(currentPage--);
}
});
builder.setView(view)
.setCancelable(true);
addDotsIndicator(0);
viewPager.setOnPageChangeListener(viewListener);
adapter = new SliderAdapter(getActivity(), text);
return builder.create();
}
private void addDotsIndicator(int position) {
dots = new TextView[3];
dotLayout.removeAllViews();
for (int i = 0; i<dots.length; i++) {
dots[i] = new TextView(getActivity());
dots[i].setText(Html.fromHtml("&#8226"));
dots[i].setTextSize(35);
dots[i].setTextColor(Color.parseColor("#404040"));
dotLayout.addView(dots[i]);
}
if(dots.length > 0) {
dots[position].setTextColor(Color.BLACK);
}
if (currentPage == 0) {
back.setEnabled(false);
next.setEnabled(true);
back.setText("");
next.setText("Next");
}
}
ViewPager.OnPageChangeListener viewListener = new ViewPager.OnPageChangeListener() {
#Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
}
#Override
public void onPageSelected(int position) {
addDotsIndicator(position);
currentPage = position;
if (currentPage == 0) {
back.setEnabled(false);
next.setEnabled(true);
back.setText("");
next.setText("Next");
} else if (currentPage == 1) {
back.setEnabled(true);
next.setEnabled(true);
back.setText("Back");
next.setText("Next");
} else if (currentPage == 2) {
back.setEnabled(true);
next.setEnabled(false);
back.setText("Back");
next.setText("Proceed");
}
}
#Override
public void onPageScrollStateChanged(int state) {
}
};
}
Dialog XML:
<RelativeLayout
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:background="#drawable/dialog_bg"
app:cardCornerRadius="20dp">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
<androidx.viewpager.widget.ViewPager
android:id="#+id/viewPager"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
<LinearLayout
android:id="#+id/dotLayout"
android:layout_width="wrap_content"
android:layout_height="30dp"
android:layout_centerHorizontal="true"
android:layout_margin="15dp"
android:layout_below="#+id/viewPager"
android:orientation="horizontal" />
<Button
android:id="#+id/back"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_margin="5dp"
android:layout_below="#+id/viewPager"
android:background="#android:color/transparent"
android:elevation="0dp"
android:text="Back"
android:textColor="#android:color/black" />
<Button
android:id="#+id/next"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentEnd="true"
android:layout_below="#+id/viewPager"
android:layout_margin="5dp"
android:background="#android:color/transparent"
android:elevation="0dp"
android:text="Next"
android:textColor="#android:color/black" />
</RelativeLayout>
ViewPager's slide layout:
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_height="match_parent"
android:background="#android:color/white">
<TextView
android:id="#+id/txt11"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="TEST"
android:textColor="#android:color/black"
android:textSize="30sp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.24000001" />
<TextView
android:id="#+id/txt22"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:gravity="center"
android:text="Test"
android:textColor="#android:color/black"
android:textSize="18sp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="#+id/txt11"
app:layout_constraintStart_toStartOf="#+id/txt11"
app:layout_constraintTop_toBottomOf="#+id/txt11"
app:layout_constraintVertical_bias="0.26" />
</androidx.constraintlayout.widget.ConstraintLayout>
The problem is that you didn't set the ViewPager adapter
public class DialogWeeklyReport extends AppCompatDialogFragment {
...
#NonNull
#Override
public Dialog onCreateDialog(#Nullable Bundle savedInstanceState) {
...
viewPager = view.findViewById(R.id.viewPager);
...
adapter = new SliderAdapter(getActivity(), text);
viewPager.setAdapter(adapter); // <<<<<< change here
return builder.create();
}
...
Here is my test

Delete Item From Recycler View on Button Click.Button is Set from outside of Recycler View?

I want a delete button outside of the RecyclerView and an Edit Text which will take user input and when I click on the Delete Button the row in the Recyclerview which matches the Edittext text should be deleted. How can I achieve this?
MainActivity.java :
public class MainActivity extends AppCompatActivity {
RecyclerView recyclerView;
Adapter adapter;
ArrayList<ModelClass> arrayList;
RecyclerView.LayoutManager layoutManager;
EditText edit_name, edit_desc;
Spinner spinner;
Button btm_save, btn_delete;
String Name, Description, Spinner;
SQLiteDatabase sqLiteDatabase;
SqliteHelper sqliteHelper;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
edit_name = findViewById(R.id.edit_name);
edit_desc = findViewById(R.id.edit_desc);
btm_save = findViewById(R.id.btn_save);
btn_delete = findViewById(R.id.btn_view);
spinner = findViewById(R.id.spinner);
sqliteHelper = new SqliteHelper(this);
sqLiteDatabase = sqliteHelper.getReadableDatabase();
ArrayAdapter<CharSequence> arrayAdapter = ArrayAdapter.createFromResource(this, R.array.Options, android.R.layout.simple_spinner_item);
arrayAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner.setAdapter(arrayAdapter);
recyclerView = findViewById(R.id.recylerView);
arrayList = new ArrayList<>();
adapter = new Adapter(this, arrayList);
recyclerView.setAdapter(adapter);
layoutManager = new LinearLayoutManager(this);
recyclerView.setLayoutManager(layoutManager);
getAllData();
edit_name.addTextChangedListener(textWatcher);
edit_desc.addTextChangedListener(textWatcher);
btm_save.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Name = edit_name.getText().toString();
Description = edit_desc.getText().toString();
Spinner = spinner.getSelectedItem().toString();
if (!ValidateUser(Name)) {
if (!TextUtils.isEmpty(Spinner)) {
ModelClass modelClass = new ModelClass(Name, Spinner, Description);
arrayList.add(modelClass);
adapter.notifyItemInserted(arrayList.size());
InsertData();
} else {
Toast.makeText(MainActivity.this, "Please Select Experience", Toast.LENGTH_SHORT).show();
}
} else {
Toast.makeText(MainActivity.this, "User name Already Exits", Toast.LENGTH_SHORT).show();
}
}
});
btn_delete.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Integer deletedRows = sqliteHelper.deleteData(edit_name.getText().toString());
if (deletedRows > 0) {
Toast.makeText(MainActivity.this, "Record Deleted", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(MainActivity.this, "Record Not Found", Toast.LENGTH_SHORT).show();
}
}
});
}
private void InsertData() {
boolean InsertSuccessfully = sqliteHelper.InsertData(Name, Description, Spinner);
if (InsertSuccessfully) {
Toast.makeText(this, "Record Inserted", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(this, "Record Not Inserted", Toast.LENGTH_SHORT).show();
}
}
public void getAllData() {
Cursor cursor = sqliteHelper.retriveData();
while (cursor.moveToNext()) {
ModelClass modelClass = new ModelClass(cursor.getString(cursor.getColumnIndex(SqliteHelper.COL_2)),
cursor.getString(cursor.getColumnIndex(SqliteHelper.COL_3)),
cursor.getString(cursor.getColumnIndex(SqliteHelper.COL_4)));
arrayList.add(modelClass);
}
}
private TextWatcher textWatcher = new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
}
#Override
public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
Name = edit_name.getText().toString();
Description = edit_desc.getText().toString();
btm_save.setEnabled(!Name.isEmpty() && !Description.isEmpty());
}
#Override
public void afterTextChanged(Editable editable) {
}
};
public boolean ValidateUser(String name) {
SQLiteDatabase database = sqliteHelper.getWritableDatabase();
Cursor cursor = database.query(SqliteHelper.TABLE_NAME, null, SqliteHelper.COL_2 + "=?", new String[]{name},
null, null, null);
int i = cursor.getCount();
if (i > 0) {
return true;
} else {
return false;
}
}
}
activity_main.xml :
<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"
tools:context=".MainActivity">
<EditText
android:id="#+id/edit_name"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="5dp"
android:layout_marginLeft="5dp"
android:layout_marginTop="10dp"
android:ems="10"
android:hint="#string/Name"
android:inputType="textPersonName"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<Spinner
android:id="#+id/spinner"
android:layout_width="120dp"
android:layout_height="50dp"
android:layout_marginTop="4dp"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.883"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<Button
android:id="#+id/btn_save"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="76dp"
android:layout_marginLeft="76dp"
android:layout_marginTop="28dp"
android:enabled="false"
android:text="Save Data"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/edit_name" />
<EditText
android:id="#+id/edit_desc"
android:layout_width="match_parent"
android:layout_height="60dp"
android:ems="10"
android:inputType="textMultiLine"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="1.0"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/btn_save" />
<androidx.recyclerview.widget.RecyclerView
android:id="#+id/recylerView"
android:layout_width="match_parent"
android:layout_height="550dp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.0"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/edit_desc"
app:layout_constraintVertical_bias="0.036" />
<Button
android:id="#+id/btn_view"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="34dp"
android:layout_marginLeft="34dp"
android:layout_marginTop="28dp"
android:layout_marginEnd="88dp"
android:layout_marginRight="88dp"
android:text="Delete Data"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toEndOf="#+id/btn_save"
app:layout_constraintTop_toBottomOf="#+id/spinner" />
</androidx.constraintlayout.widget.ConstraintLayout>
If your item gets deleted using the code you have used, then you just need to refresh your list:
btn_delete.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Integer deletedRows = sqliteHelper.deleteData(edit_name.getText().toString());
if (deletedRows > 0) {
Toast.makeText(MainActivity.this, "Record Deleted", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(MainActivity.this, "Record Not Found", Toast.LENGTH_SHORT).show();
}
getAllData();
adapter.notifyDataSetChanged();
}
});
Find the string in your ArrayList of modelClass object, once found look that index and remove that entry from the array list and notify the same to recyclerView's adapter.
int count = 0;
for(ModelClass mod : arrayList) {
if(mod.name.equalsIgnoreCase(editText.getString)) {
arrayList.remove(mod);
adapter.notifyItemRemoved(count);
break;
}
count++;
}

Android crashing on empty EText

The app keeps crashing whenever edit Text is empty. When I enter an e-mail it works fine. I don't know what I'm doing wrong, I already tried changing height value, checked manually when it's empty but still, the issue remains. Can anyone please let me know if there's something wrong with the code.
Error:
--------- beginning of crash
09-07 10:39:53.791 15985-15985/com.app.androidnewsapp E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.app.androidnewsapp, PID: 15985
android.view.InflateException: Binary XML file line #17: Binary XML file line #17: Error inflating class TextView
at android.view.LayoutInflater.inflate(LayoutInflater.java:539)
at android.view.LayoutInflater.inflate(LayoutInflater.java:423)
at android.view.LayoutInflater.inflate(LayoutInflater.java:374)
at android.widget.Editor.showError(Editor.java:430)
at android.widget.Editor.setError(Editor.java:466)
at android.widget.TextView.setError(TextView.java:4960)
at android.widget.TextView.setError(TextView.java:4945)
at com.app.androidnewsapp.activities.ActivityForgotPassword.onValidationFailed(ActivityForgotPassword.java:132)
at com.app.androidnewsapp.utils.validation.Validator$1.onPostExecute(Validator.java:195)
at com.app.androidnewsapp.utils.validation.Validator$1.onPostExecute(Validator.java:183)
at android.os.AsyncTask.finish(AsyncTask.java:651)
at android.os.AsyncTask.access$500(AsyncTask.java:180)
at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:668)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:168)
at android.app.ActivityThread.main(ActivityThread.java:5885)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:797)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:687)
Caused by: android.view.InflateException: Binary XML file line #17: Error inflating class TextView
at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:782)
at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:704)
at android.view.LayoutInflater.inflate(LayoutInflater.java:492)
at android.view.LayoutInflater.inflate(LayoutInflater.java:423) 
at android.view.LayoutInflater.inflate(LayoutInflater.java:374) 
at android.widget.Editor.showError(Editor.java:430) 
at android.widget.Editor.setError(Editor.java:466) 
at android.widget.TextView.setError(TextView.java:4960) 
at android.widget.TextView.setError(TextView.java:4945) 
at com.app.androidnewsapp.activities.ActivityForgotPassword.onValidationFailed(ActivityForgotPassword.java:132) 
at com.app.androidnewsapp.utils.validation.Validator$1.onPostExecute(Validator.java:195) 
at com.app.androidnewsapp.utils.validation.Validator$1.onPostExecute(Validator.java:183) 
at android.os.AsyncTask.finish(AsyncTask.java:651) 
at android.os.AsyncTask.access$500(AsyncTask.java:180) 
at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:668) 
at android.os.Handler.dispatchMessage(Handler.java:102) 
at android.os.Looper.loop(Looper.java:168) 
at android.app.ActivityThread.main(ActivityThread.java:5885) 
at java.lang.reflect.Method.invoke(Native Method) 
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:797) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:687) 
Caused by: java.lang.UnsupportedOperationException: Failed to resolve attribute at index 24: TypedValue{t=0x3/d=0x4a3 "res/color/secondary_text_material_light.xml" a=1 r=0x106011a}
at android.content.res.TypedArray.getColor(TypedArray.java:447)
at android.widget.TextView.<init>(TextView.java:753)
Code:
#Required(order = 1)
#Email(order = 2, message = "Please Check and Enter a valid Email Address")
EditText edtEmail;
String strEmail, strMessage;
private Validator validator;
Button btn_forgot;
ProgressBar progressBar;
LinearLayout layout;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_user_forgot);
if (Config.ENABLE_RTL_MODE) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
getWindow().getDecorView().setLayoutDirection(View.LAYOUT_DIRECTION_RTL);
}
}
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
Window window = getWindow();
window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
window.setStatusBarColor(Color.BLACK);
}
edtEmail = findViewById(R.id.etUserName);
btn_forgot = findViewById(R.id.btnForgot);
progressBar = findViewById(R.id.progressBar);
layout = findViewById(R.id.view);
btn_forgot.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
validator.validateAsync();
}
});
validator = new Validator(this);
validator.setValidationListener(this);
setupToolbar();
}
public void setupToolbar() {
final Toolbar toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
final ActionBar actionBar = getSupportActionBar();
if (actionBar != null) {
getSupportActionBar().setDisplayHomeAsUpEnabled(false);
getSupportActionBar().setHomeButtonEnabled(false);
getSupportActionBar().setTitle("");
}
AppBarLayout appBarLayout = findViewById(R.id.appBarLayout);
if (appBarLayout.getLayoutParams() != null) {
CoordinatorLayout.LayoutParams layoutParams = (CoordinatorLayout.LayoutParams) appBarLayout.getLayoutParams();
AppBarLayout.Behavior appBarLayoutBehaviour = new AppBarLayout.Behavior();
appBarLayoutBehaviour.setDragCallback(new AppBarLayout.Behavior.DragCallback() {
#Override
public boolean canDrag(#NonNull AppBarLayout appBarLayout) {
return false;
}
});
layoutParams.setBehavior(appBarLayoutBehaviour);
}
}
#Override
public void onValidationSucceeded() {
strEmail = edtEmail.getText().toString();
if (NetworkCheck.isNetworkAvailable(ActivityForgotPassword.this)) {
new MyTaskForgot().execute(Constant.FORGET_PASSWORD_URL + strEmail);
} else {
Toast.makeText(getApplicationContext(), getResources().getString(R.string.msg_no_network), Toast.LENGTH_SHORT).show();
}
}
#Override
public void onValidationFailed(View failedView, Rule<?> failedRule) {
String message = failedRule.getFailureMessage();
if (failedView instanceof EditText) {
failedView.requestFocus();
((EditText) failedView).setError(message);
} else {
Toast.makeText(this, "Record Not Saved", Toast.LENGTH_SHORT).show();
}
}
#Override
public void onBackPressed() {
//Log.d(TAG, "onBackPressed: Si entra +++++++++");
// moveTaskToBack(true);
startActivity(new Intent(getApplicationContext(), ActivityUserLogin.class));
finish();
}
private class MyTaskForgot extends AsyncTask<String, Void, String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
progressBar.setVisibility(View.VISIBLE);
layout.setVisibility(View.INVISIBLE);
}
#Override
protected String doInBackground(String... params) {
return NetworkCheck.getJSONString(params[0]);
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
if (null == result || result.length() == 0) {
Toast.makeText(getApplicationContext(), getResources().getString(R.string.msg_no_network), Toast.LENGTH_SHORT).show();
} else {
try {
JSONObject mainJson = new JSONObject(result);
JSONArray jsonArray = mainJson.getJSONArray(Constant.CATEGORY_ARRAY_NAME);
JSONObject objJson = null;
for (int i = 0; i < jsonArray.length(); i++) {
objJson = jsonArray.getJSONObject(i);
strMessage = objJson.getString(Constant.MSG);
Constant.GET_SUCCESS_MSG = objJson.getInt(Constant.SUCCESS);
}
} catch (JSONException e) {
e.printStackTrace();
}
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
progressBar.setVisibility(View.GONE);
setResult();
}
}, Constant.DELAY_PROGRESS_DIALOG);
}
}
}
public void setResult() {
if (Constant.GET_SUCCESS_MSG == 0) {
AlertDialog.Builder dialog = new AlertDialog.Builder(this);
dialog.setTitle(R.string.whops);
dialog.setMessage(R.string.forgot_failed_message);
dialog.setPositiveButton(R.string.dialog_ok, null);
dialog.setCancelable(false);
dialog.show();
layout.setVisibility(View.VISIBLE);
edtEmail.setText("");
edtEmail.requestFocus();
} else {
AlertDialog.Builder dialog = new AlertDialog.Builder(this);
dialog.setTitle(R.string.dialog_success);
dialog.setMessage(R.string.forgot_success_message);
dialog.setPositiveButton(R.string.dialog_ok, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
Intent intent = new Intent(ActivityForgotPassword.this, ActivityUserLogin.class);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(intent);
finish();
}
});
dialog.setCancelable(false);
dialog.show();
}
}
#Override
public boolean onOptionsItemSelected(MenuItem menuItem) {
switch (menuItem.getItemId()) {
case android.R.id.home:
onBackPressed();
break;
default:
return super.onOptionsItemSelected(menuItem);
}
return true;
}
XML:
<android.support.design.widget.CoordinatorLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:focusableInTouchMode="true">
<android.support.design.widget.AppBarLayout
android:id="#+id/appBarLayout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:fitsSystemWindows="true"
android:theme="#style/ThemeOverlay.AppCompat.ActionBar">
<android.support.design.widget.CollapsingToolbarLayout
android:id="#+id/collapsingToolbarLayout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:fitsSystemWindows="true"
android:background="#color/colorBlackary"
app:contentScrim="?attr/colorPrimary"
app:layout_scrollFlags="scroll|enterAlways|enterAlwaysCollapsed"
app:titleEnabled="false">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:layout_marginTop="5dp"
android:padding="10dp"
android:text="#string/title_forgot_password"
android:textColor="#color/colorRed"
android:textSize="15sp" />
<android.support.v7.widget.Toolbar
android:id="#+id/toolbar"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:layout_collapseMode="pin"
app:theme="#style/ThemeOverlay.AppCompat.Dark.ActionBar" />
</android.support.design.widget.CollapsingToolbarLayout>
</android.support.design.widget.AppBarLayout>
<android.support.v7.widget.CardView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="10dp"
android:foreground="?android:attr/selectableItemBackground"
app:behavior_overlapTop="64dp"
app:cardCornerRadius="3dp"
app:layout_behavior="#string/appbar_scrolling_view_behavior"
card_view:cardElevation="6sp"
card_view:cardPreventCornerOverlap="false"
card_view:cardUseCompatPadding="true">
<RelativeLayout
android:id="#+id/lyt_form"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true">
<ImageView
android:layout_width="match_parent"
android:layout_height="470dp"
android:scaleType="fitXY"
android:src="#drawable/fondopeleadorkary" />
<LinearLayout
android:id="#+id/view"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:orientation="vertical"
android:padding="20dp">
<android.support.design.widget.TextInputLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:theme="#style/TextLabel">
<EditText
android:id="#+id/etUserName"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="10dp"
android:layout_marginTop="20dp"
android:drawablePadding="15dp"
android:hint="#string/edt_email"
android:textColor="#color/colorWhite"
android:inputType="textEmailAddress" />
</android.support.design.widget.TextInputLayout>
<TextView
android:id="#+id/textView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="10dp"
android:gravity="center"
android:textColor="#color/colorWhite"
android:text="#string/forgot_message" />
<com.balysv.materialripple.MaterialRippleLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="10dp"
android:layout_marginTop="20dp"
app:mrl_rippleAlpha="0.2"
app:mrl_rippleColor="#color/colorRipple"
app:mrl_rippleHover="true"
app:mrl_rippleOverlay="true">
<Button
android:id="#+id/btnForgot"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:background="#color/colorRed"
android:text="#string/btn_send"
android:textColor="#color/colorWhite"
android:textStyle="bold" />
</com.balysv.materialripple.MaterialRippleLayout>
</LinearLayout>
<ProgressBar
android:id="#+id/progressBar"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
android:visibility="gone" />
</RelativeLayout>
</android.support.v7.widget.CardView>
</android.support.design.widget.CoordinatorLayout>
Try this
#Override
public void onValidationFailed(View failedView, Rule<?> failedRule) {
String message = failedRule.getFailureMessage();
if (failedView instanceof EditText) {
failedView.requestFocus();
if(!TextUtils.isEmpty(message){
((EditText) failedView).setError(message);
}
} else {
Toast.makeText(this, "Record Not Saved", Toast.LENGTH_SHORT).show();
}
I found the problem :
android:theme="#style/TextLabel"
Had to create a theme first and than a style and use it like :
<style name="TextLabel" parent="BellicTheme">
Thanks everyone

error: java.lang.ClassCastException: android.view.View cannot be cast to android.view.ViewGroup

I'm trying to cast a database into a ListView, and when tapped on, for it to reveal more information, but I started getting the error in the title once I added the expandable functionality.
Here's my list_item.xml, seemingly the source of the problems:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:padding="#dimen/activity_horizontal_margin">
<TextView
android:id="#+id/name"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:paddingBottom="2dip"
android:textColor="#color/colorAccent"/>
<View
android:layout_width="0px"
android:layout_height="0px"
android:id="#+id/expandable">
<TextView
android:id="#+id/description"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textColor="#5d5d5d"
android:textStyle="bold"/>
<TextView
android:id="#+id/email"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textColor="#5d5d40"
android:textStyle="bold" />
<TextView
android:id="#+id/telephone"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textColor="#5d5d40"
android:textStyle="bold" />
</View>
</LinearLayout>
And here's MainActivity2.java (temp name):
public class MainActivity2 extends Activity {
private String TAG = MainActivity2.class.getSimpleName();
private ListView lv;
private View ex;
ArrayList<HashMap<String, String>> contactList;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
contactList = new ArrayList<>();
lv = (ListView) findViewById(R.id.list);
new GetContacts().execute();
ex = findViewById(R.id.expandable);
lv.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
public void onItemSelected(AdapterView parentView, View childView,
int position, long id)
{
expand(ex);
}
public void onNothingSelected(AdapterView parentView) {
}
});
}
public static void expand(final View v) {
v.measure(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT);
final int targetHeight = v.getMeasuredHeight();
// Older versions of android (pre API 21) cancel animations for views with a height of 0.
v.getLayoutParams().height = 1;
v.setVisibility(View.VISIBLE);
Animation a = new Animation()
{
#Override
protected void applyTransformation(float interpolatedTime, Transformation t) {
v.getLayoutParams().height = interpolatedTime == 1
? LinearLayout.LayoutParams.WRAP_CONTENT
: (int)(targetHeight * interpolatedTime);
v.requestLayout();
}
#Override
public boolean willChangeBounds() {
return true;
}
};
// 1dp/ms
a.setDuration((int)(targetHeight / v.getContext().getResources().getDisplayMetrics().density));
v.startAnimation(a);
}
public static void collapse(final View v) {
final int initialHeight = v.getMeasuredHeight();
Animation a = new Animation()
{
#Override
protected void applyTransformation(float interpolatedTime, Transformation t) {
if(interpolatedTime == 1){
v.setVisibility(View.GONE);
}else{
v.getLayoutParams().height = initialHeight - (int)(initialHeight * interpolatedTime);
v.requestLayout();
}
}
#Override
public boolean willChangeBounds() {
return true;
}
};
// 1dp/ms
a.setDuration((int)(initialHeight / v.getContext().getResources().getDisplayMetrics().density));
v.startAnimation(a);
}
private class GetContacts extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
Toast.makeText(MainActivity2.this,"Json Data is downloading",Toast.LENGTH_LONG).show();
}
#Override
protected Void doInBackground(Void... arg0) {
HttpHandler sh = new HttpHandler();
// Making a request to url and getting response
String url = "https://s3-eu-west-1.amazonaws.com/tyi-work/Work_Experience.json";
String jsonStr = sh.makeServiceCall(url);
Log.e(TAG, "Response from url: " + jsonStr);
if (jsonStr != null) {
try {
JSONObject jsonObj = new JSONObject(jsonStr);
// Getting JSON Array node
JSONArray contacts = jsonObj.getJSONArray("work");
// looping through All Contacts
for (int i = 0; i < contacts.length(); i++) {
JSONObject c = contacts.getJSONObject(i);
String id = c.getString("id");
String name = c.getString("name");
String email = c.getString("email");
String address = c.getString("address");
String telephone = c.getString("telephone");
// Phone node is JSON Object
String description = c.getString("description");
String agerange = c.getString("agerange");
String county = c.getString("county");
String category = c.getString("category");
String website = c.getString("website");
// tmp hash map for single contact
HashMap<String, String> contact = new HashMap<>();
// adding each child node to HashMap key => value
contact.put("description", description);
contact.put("name", name);
contact.put("email", email);
contact.put("telephone", telephone);
// adding contact to contact list
contactList.add(contact);
}
} catch (final JSONException e) {
Log.e(TAG, "Json parsing error: " + e.getMessage());
runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(getApplicationContext(),
"Json parsing error: " + e.getMessage(),
Toast.LENGTH_LONG).show();
}
});
}
} else {
Log.e(TAG, "Couldn't get json from server.");
runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(getApplicationContext(),
"Couldn't get json from server. Check LogCat for possible errors!",
Toast.LENGTH_LONG).show();
}
});
}
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
ListAdapter adapter = new SimpleAdapter(MainActivity2.this, contactList,
R.layout.list_item, new String[]{ "email","description","name"},
new int[]{R.id.email, R.id.description, R.id.name});
lv.setAdapter(adapter);
}
}
}
If any more information is needed, I will happily provide it.
Thank You in advance
EDIT:
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.teamplum.projectapple, PID: 12076
java.lang.ClassCastException: android.view.View cannot be cast to android.view.ViewGroup
at android.view.LayoutInflater.rInflate(LayoutInflater.java:826)
at android.view.LayoutInflater.rInflate(LayoutInflater.java:828)
at android.view.LayoutInflater.inflate(LayoutInflater.java:523)
at android.view.LayoutInflater.inflate(LayoutInflater.java:425)
at android.widget.SimpleAdapter.createViewFromResource(SimpleAdapter.java:121)
at android.widget.SimpleAdapter.getView(SimpleAdapter.java:114)
at android.widget.AbsListView.obtainView(AbsListView.java:2481)
at android.widget.ListView.measureHeightOfChildren(ListView.java:1289)
at android.widget.ListView.onMeasure(ListView.java:1197)
at android.view.View.measure(View.java:17970)
at android.widget.RelativeLayout.measureChild(RelativeLayout.java:816)
at android.widget.RelativeLayout.onMeasure(RelativeLayout.java:561)
at android.view.View.measure(View.java:17970)
at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5710)
at android.widget.FrameLayout.onMeasure(FrameLayout.java:465)
at android.view.View.measure(View.java:17970)
at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5710)
at android.widget.LinearLayout.measureChildBeforeLayout(LinearLayout.java:1723)
at android.widget.LinearLayout.measureVertical(LinearLayout.java:785)
at android.widget.LinearLayout.onMeasure(LinearLayout.java:654)
at android.view.View.measure(View.java:17970)
at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5710)
at android.widget.FrameLayout.onMeasure(FrameLayout.java:465)
at com.android.internal.policy.impl.PhoneWindow$DecorView.onMeasure(PhoneWindow.java:2755)
at android.view.View.measure(View.java:17970)
at android.view.ViewRootImpl.performMeasure(ViewRootImpl.java:2438)
at android.view.ViewRootImpl.measureHierarchy(ViewRootImpl.java:1418)
at android.view.ViewRootImpl.performTraversals(ViewRootImpl.java:1642)
at android.view.ViewRootImpl.doTraversal(ViewRootImpl.java:1296)
at android.view.ViewRootImpl$TraversalRunnable.run(ViewRootImpl.java:6742)
at android.view.Choreographer$CallbackRecord.run(Choreographer.java:826)
at android.view.Choreographer.doCallbacks(Choreographer.java:629)
at android.view.Choreographer.doFrame(Choreographer.java:597)
at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:812)
at android.os.Handler.handleCallback(Handler.java:815)
at android.os.Handler.dispatchMessage(Handler.java:104)
at android.os.Looper.loop(Looper.java:194)
at android.app.ActivityThread.main(ActivityThread.java:5931)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:987)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:782)
this error says that you are putting views inside <View>. change this view to a ViewGroup (e.g linearLayout or RelativeLayout ) and your problem will disappear.
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:padding="#dimen/activity_horizontal_margin">
<TextView
android:id="#+id/name"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:paddingBottom="2dip"
android:textColor="#color/colorAccent"/>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent" <!-- edit this height and width-->
<!--also add orientation-->
android:id="#+id/expandable">
<TextView
android:id="#+id/description"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textColor="#5d5d5d"
android:textStyle="bold"/>
<TextView
android:id="#+id/email"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textColor="#5d5d40"
android:textStyle="bold" />
<TextView
android:id="#+id/telephone"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textColor="#5d5d40"
android:textStyle="bold" />
</LinearLayout>
</LinearLayout>

Add Progress bar while data loading from database

I use volley library to get data from database i use this code
public class R_arabic extends AppCompatActivity {
RequestQueue requestQueue;
ListView listView;
ArrayList<listitem_gib> listitems = new ArrayList<listitem_gib>();
String name, img, url, num;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_r_arabic);
listView = (ListView) findViewById(R.id.listView);
TextView textView_Title = (TextView) findViewById(R.id.textView2);
Intent intent = getIntent();
String story_type = intent.getStringExtra("story_type");
switch (story_type) {
case "arabic":
textView_Title.setText("arabic");
break;
case "romance":
textView_Title.setText("romance");
break;
case "motrgm":
textView_Title.setText("motrgm");
break;
case "ro3b":
textView_Title.setText("ro3b");
break;
case "siasa":
textView_Title.setText("siasa");
break;
}
String url = "http://grassyhat.com/android/" + story_type + ".php";
requestQueue = Volley.newRequestQueue(this);
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.GET, url,
new Response.Listener<JSONObject>() {
public void onResponse(JSONObject response) {
try {
JSONArray jsonArray = response.getJSONArray("all");
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject respons = jsonArray.getJSONObject(i);
String id = respons.getString("id");
String name = respons.getString("name");
String img = respons.getString("img");
String url = respons.getString("url");
String num = respons.getString("num");
listitems.add(new listitem_gib(id, name, img, url, num));
}
} catch (JSONException e) {
e.printStackTrace();
}
listAllItme();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e("VOLLEY", "ERROR");
}
}
);
requestQueue.add(jsonObjectRequest);
}
public void listAllItme() {
ListAdapter lA = new listAdapter(listitems);
listView.setAdapter(lA);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
CheckInternetConnection cic = new CheckInternetConnection(getApplicationContext());
Boolean Ch = cic.isConnectingToInternet();
if (!Ch) {
Toast.makeText(R_arabic.this, "no connection", Toast.LENGTH_LONG).show();
} else {
Intent open = new Intent(R_arabic.this, rewaya_show.class);
open.putExtra("name", listitems.get(position).name);
open.putExtra("url", listitems.get(position).url);
open.putExtra("img", listitems.get(position).img);
open.putExtra("num", listitems.get(position).num);
startActivity(open);
showad++;
if (showad >= 5) {
showad = 0;
if (mInterstitialAd.isLoaded()) {
mInterstitialAd.show();
}
}
}
}
});
}
class listAdapter extends BaseAdapter {
ArrayList<listitem_gib> lista = new ArrayList<listitem_gib>();
public listAdapter(ArrayList<listitem_gib> lista) {
this.lista = lista;
}
#Override
public int getCount() {
return lista.size();
}
#Override
public Object getItem(int position) {
return lista.get(position).name;
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
LayoutInflater layoutInflater = getLayoutInflater();
View view = layoutInflater.inflate(R.layout.row_item_gib, null);
TextView name = (TextView) view.findViewById(R.id.textView_gib);
ImageView img = (ImageView) view.findViewById(R.id.imageView_gib);
TextView num = (TextView) view.findViewById(R.id.textView_gib2);
name.setText(lista.get(position).name);
num.setText(lista.get(position).num);
Picasso.with(R_arabic.this).load("http://grassyhat.com/android/image/" + lista.get(position).img).into(img);
return view;
}
}
i want to add progress bar while data loading to avoid blank page
sorry i'm new in android and i google for that and don't get useful answer
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout 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"
xmlns:ads="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.kamal.ahmed.rewaya.R_arabic"
app:layout_behavior="#string/appbar_scrolling_view_behavior"
android:background="#drawable/bg"
tools:showIn="#layout/app_bar_r_arabic">
<LinearLayout
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_above="#+id/adView">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:textSize="40sp"
android:textStyle="bold"
android:textColor="#e873400c"
android:layout_gravity="center"
android:id="#+id/textView2" />
<ListView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/listView"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:paddingRight="#dimen/activity_horizontal_margin"
android:divider="#drawable/div1"
android:dividerHeight="35dp" />
</LinearLayout>
<LinearLayout
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/progress_layout"
android:visibility="gone">
<ProgressBar
android:id="#+id/progress_bar"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:layout_marginLeft="100dp"
android:layout_marginBottom="60dp"
android:layout_weight="1"/>
<TextView
android:text="Download"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/progress_txt"
android:textSize="30sp"
android:textStyle="bold"
android:textColor="#e873400c"
android:layout_gravity="center"
android:layout_marginRight="90dp"
android:layout_marginBottom="60dp"
android:layout_weight="1" />
</LinearLayout>
Add progressBar in your activity_r_arabic
<ProgressBar
android:id="#+id/progress_bar"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
add ProgessBar progressBar; as global variable in your activity
and initialise it as
progressBar = (ProgessBar) findViewById(R.id.progress_bar);
and then In onResponse(JSONObject response) method add following line
progressBar.setVisibility(View.GONE)
EDIT
Make your linearLayout visible in xml
<LinearLayout
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/progress_layout"
android:visibility="visible">
<ProgressBar
android:id="#+id/progress_bar"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:layout_marginLeft="100dp"
android:layout_marginBottom="60dp"
android:layout_weight="1"/>
<TextView
android:text="Download"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/progress_txt"
android:textSize="30sp"
android:textStyle="bold"
android:textColor="#e873400c"
android:layout_gravity="center"
android:layout_marginRight="90dp"
android:layout_marginBottom="60dp"
android:layout_weight="1" />
</LinearLayout>
and inside onResponse(JSONObject response) method add following line
progress_layout.setVisibility(View.GONE)

Categories