How to create MAD army base droid? - crud

DBHELPER..........}}}}}}}}}
package com.example.userlap.model2;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import java.lang.reflect.Array;
import java.util.ArrayList;
import java.util.List;
public class DBHelper extends SQLiteOpenHelper {
public static final String Database="Model.db";
public DBHelper(Context context) {
super(context, Database, null, 1);
//SQLiteDatabase db=this.getWritableDatabase() ;
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("create table "+ UserProfile.Users.TableName+" ("+ UserProfile.Users.Col_1+" Integer primary key AUTOINCREMENT,"+ UserProfile.Users.Col_2 +" TEXT,"+ UserProfile.Users.Col_3 +" TEXT,"+ UserProfile.Users.Col_4 +" TEXT,"+ UserProfile.Users.Col_5 +" TEXT)");
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("Drop table if exists "+ UserProfile.Users.TableName);
onCreate(db);
}
public boolean addInfo(String uname,String DOb,String password,String Gender){
SQLiteDatabase db=this.getWritableDatabase();
ContentValues cv=new ContentValues();
cv.put(UserProfile.Users.Col_2,uname);
cv.put(UserProfile.Users.Col_3,DOb);
cv.put(UserProfile.Users.Col_4,password);
cv.put(UserProfile.Users.Col_5,Gender);
long ans=db.insert(UserProfile.Users.TableName,null,cv);
if(ans==-1){
return false;
}
else
return true;
}
public boolean updateInfor(int id,String uname,String DOb,String password,String Gender){
SQLiteDatabase db=this.getWritableDatabase();
ContentValues cv=new ContentValues();
cv.put(UserProfile.Users.Col_2,uname);
cv.put(UserProfile.Users.Col_3,DOb);
cv.put(UserProfile.Users.Col_4,password);
cv.put(UserProfile.Users.Col_5,Gender);
long ans=db.update(UserProfile.Users.TableName,cv,"UserInfo="+id,null);
if(ans==-1){
return false;
}
else
return true;
}
public List readAllInfor(){
SQLiteDatabase db=this.getWritableDatabase();
Cursor cus=db.rawQuery("Select * from "+ UserProfile.Users.TableName,null);
ArrayList<ui> list=new ArrayList<>();
if(cus.getCount()>0){
while (cus.moveToNext()){
ui ui1=new ui();
ui1.setID(cus.getInt(0));
ui1.setUsename(cus.getString(1));
ui1.setDOB(cus.getString(2));
ui1.setPasssword(cus.getString(3));
ui1.setGender(cus.getString(4));
list.add(ui1);
}
}
return list;
}
public List readAllInfor(int id){
SQLiteDatabase db=this.getWritableDatabase();
Cursor cus=db.rawQuery("Select * from "+ UserProfile.Users.TableName+" where _ID="+id,null);
ArrayList<ui> list=new ArrayList<>();
if(cus.getCount()>0){
while (cus.moveToNext()){
ui ui1=new ui();
ui1.setID(cus.getInt(0));
ui1.setUsename(cus.getString(1));
ui1.setDOB(cus.getString(2));
ui1.setPasssword(cus.getString(3));
ui1.setGender(cus.getString(4));
list.add(ui1);
}
}
return list;
}
public Integer deleteInfo(int id){
SQLiteDatabase db=this.getWritableDatabase();
return db.delete(UserProfile.Users.TableName,"_ID=?"+id,null);
}
}
USERPROFILE-----------------------------------------------------
package com.example.userlap.model2;
import android.provider.BaseColumns;
public class UserProfile {
private UserProfile() {
}
public final static class Users implements BaseColumns{
public static final String Col_1="_ID";
public static final String Col_2="userName";
public static final String Col_3="dateOfBirth";
public static final String Col_4="Password";
public static final String Col_5="Gender";
public static final String TableName="UserInfo";
}
}
HOME---------------------------------------------------
package com.example.userlap.model2;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import java.util.ArrayList;
public class Home extends AppCompatActivity {
DBHelper mydb;
Button register,login;
EditText id,pw;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home);
mydb=new DBHelper(this);
register=(Button)findViewById(R.id.button2);
login=(Button)findViewById(R.id.button) ;
id=(EditText)findViewById(R.id.editText);
pw=(EditText)findViewById(R.id.editText2);
login();
register.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent i1=new Intent(Home.this,ProfileManagement.class);
startActivity(i1);
}
});
}
public void login(){
login.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
ArrayList<ui> list=(ArrayList<ui>)mydb.readAllInfor(Integer.parseInt(id.getText().toString()));
if(!list.isEmpty()){
for(ui u:list){
if(u.getID()==Integer.parseInt(id.getText().toString()) && u.getPasssword().equals(pw.getText().toString())){
Intent i1=new Intent(Home.this,EditProfile.class);
startActivity(i1);
}
}
}
}
});
}
}
ProfileManagement----------------------------
package com.example.userlap.model2;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.Toast;
public class ProfileManagement extends AppCompatActivity {
Button edit,register;
EditText uname,pass,dob;
DBHelper mydb;
RadioButton type;
RadioGroup gender;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_profile_management);
mydb=new DBHelper(this);
edit=(Button)findViewById(R.id.button6);
register=(Button)findViewById(R.id.button7);
uname=(EditText)findViewById(R.id.editText6);
pass=(EditText)findViewById(R.id.editText7);
dob=(EditText)findViewById(R.id.editText8);
gender=(RadioGroup)findViewById(R.id.radioGroup2);
edit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent i2=new Intent(ProfileManagement.this,EditProfile.class);
startActivity(i2);
}
});
register.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
boolean res= mydb.addInfo(uname.getText().toString(),dob.getText().toString(),pass.getText().toString(),gtype(gender));
if(res=true){
Toast.makeText(ProfileManagement.this,"Successful",Toast.LENGTH_LONG).show();
}
else
Toast.makeText(ProfileManagement.this,"NOT ",Toast.LENGTH_LONG).show();
}
});
}
public String gtype(View v){
int res=gender.getCheckedRadioButtonId();
type=(RadioButton)findViewById(res);
return type.getText().toString();
}
}
EditProfile-----------------------------------------------------------
package com.example.userlap.model2;
import android.database.Cursor;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import java.util.ArrayList;
public class EditProfile extends AppCompatActivity {
Button search,edit,delete;
DBHelper mydb;
RadioButton type,male,female;
RadioGroup gender;
EditText uname,pass,dob,id;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mydb=new DBHelper(this);
//ArrayList<ui> list11=new ArrayList<>();
setContentView(R.layout.activity_edit_profile);
search=(Button)findViewById(R.id.button3);
edit=(Button)findViewById(R.id.button4);
delete=(Button)findViewById(R.id.button5);
uname=(EditText)findViewById(R.id.editText3);
pass=(EditText)findViewById(R.id.editText5);
dob=(EditText)findViewById(R.id.editText4);
gender=(RadioGroup)findViewById(R.id.radioGroup);
id=(EditText)findViewById(R.id.editText9);
male=(RadioButton)findViewById(R.id.radioButton);
female=(RadioButton)findViewById(R.id.radioButton2);
search.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
ArrayList<ui> list11= (ArrayList<ui>) mydb.readAllInfor(Integer.parseInt(id.getText().toString()));
if(!list11.isEmpty()){
for(ui i:list11){
uname.setText(i.getUsename());
pass.setText(i.getPasssword());
dob.setText(i.getDOB());
if(i.getGender().equals("Male")){
male.setChecked(true);
}
else
female.setChecked(true);
}
}
}
});
}
public String gtype(View v){
int res=gender.getCheckedRadioButtonId();
type=(RadioButton)findViewById(res);
return type.getText().toString();
}
}
ui-----------------------------------------------------------------------------------
package com.example.userlap.model2;
public class ui {
private String usename;
public int getID() {
return ID;
}
public void setID(int ID) {
this.ID = ID;
}
private int ID;
private String Passsword;
private String DOB;
private String Gender;
public String getUsename() {
return usename;
}
public void setUsename(String usename) {
this.usename = usename;
}
public String getPasssword() {
return Passsword;
}
public void setPasssword(String passsword) {
Passsword = passsword;
}
public String getDOB() {
return DOB;
}
public void setDOB(String DOB) {
this.DOB = DOB;
}
public String getGender() {
return Gender;
}
public void setGender(String gender) {
Gender = gender;
}
}

selecting a single record
public List readAllInfor(int id){
SQLiteDatabase db=this.getWritableDatabase();
Cursor cus=db.rawQuery("Select * from "+ UserProfile.Users.TableName+" where _ID="+id,null);
ArrayList<ui> list=new ArrayList<>();
if(cus.getCount()>0){
while (cus.moveToNext()){
ui ui1=new ui();
ui1.setID(cus.getInt(0));
ui1.setUsename(cus.getString(1));
ui1.setDOB(cus.getString(2));
ui1.setPasssword(cus.getString(3));
ui1.setGender(cus.getString(4));
list.add(ui1);
}
}
return list;
}
-- Calling it
ArrayList<ui> list11= (ArrayList<ui>) mydb.readAllInfor(Integer.parseInt(id.getText().toString()));
if(!list11.isEmpty()){
for(ui i:list11){
uname.setText(i.getUsename());
pass.setText(i.getPasssword());
dob.setText(i.getDOB());
if(i.getGender().equals("Male")){
male.setChecked(true);
}
else
female.setChecked(true);
Selecting all records
public List readAllInfor(){
SQLiteDatabase db=this.getWritableDatabase();
Cursor cus=db.rawQuery("Select * from "+ UserProfile.Users.TableName,null);
ArrayList<ui> list=new ArrayList<>();
if(cus.getCount()>0){
while (cus.moveToNext()){
ui ui1=new ui();
ui1.setID(cus.getInt(0));
ui1.setUsename(cus.getString(1));
ui1.setDOB(cus.getString(2));
ui1.setPasssword(cus.getString(3));
ui1.setGender(cus.getString(4));
list.add(ui1);
}
}
return list;
}
--calling it
ArrayList<ui> list11= (ArrayList<ui>) mydb.readAllInfor();
if(!list11.isEmpty()){
for(ui i:list11){
uname.setText(i.getUsename());
pass.setText(i.getPasssword());
dob.setText(i.getDOB());
if(i.getGender().equals("Male")){
male.setChecked(true);
}
else
female.setChecked(true);

-- USING CURSORS --
Selecting a single Record
public MovieDetailsVO getMovie(int movie_id) {
MovieDetailsVO movieDetails = new MovieDetailsVO();
SQLiteDatabase db = this.getReadableDatabase();
//specify the columns to be fetched
String[] columns = {KEY_MOVIE_ID, KEY_MOVIE_NAME, KEY_GENRE, KEY_YEAR, KEY_RATING};
//Select condition
String selection = KEY_MOVIE_ID + " = ?";
//Arguments for selection
String[] selectionArgs = {String.valueOf(movie_id)};
Cursor cursor = db.query(TABLE_NAME, columns, selection,
selectionArgs, null, null, null);
if (null != cursor) {
cursor.moveToFirst();
movieDetails.setMovieId(cursor.getInt(0));
movieDetails.setMovieName(cursor.getString(1));
movieDetails.setGenre(cursor.getString(2));
movieDetails.setYear(cursor.getInt(3));
movieDetails.setRating(cursor.getDouble(4));
}
db.close();
return movieDetails;
}
Retrieving all Records
public List getAllMovies() {
List movieDetailsList = new ArrayList();
String selectQuery = "SELECT * FROM " + TABLE_NAME
+ " ORDER BY " + KEY_MOVIE_ID + " DESC";
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
//if TABLE has rows
if (cursor.moveToFirst()) {
//Loop through the table rows
do {
MovieDetailsVO movieDetails = new MovieDetailsVO();
movieDetails.setMovieId(cursor.getInt(0));
movieDetails.setMovieName(cursor.getString(1));
movieDetails.setGenre(cursor.getString(2));
movieDetails.setYear(cursor.getInt(3));
movieDetails.setRating(cursor.getDouble(4));
//Add movie details to list
movieDetailsList.add(movieDetails);
} while (cursor.moveToNext());
}
db.close();
return movieDetailsList;
}

Related

How is it possible to reach a checkbox or something else object from an other class

I have a list application what uses Recyclerview. All line have an checkbox, 2pcs TextView and a button. These are declarated in the RecyclerView class.
The application has got an other class what handles the data for example SharedPreferences, and calculations and so on...
How is it possible that I reach the objects what are in RecyclerView from the other class.
Here is the RecyclerView class:
package com.example.homehandling;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.TextView;
import android.widget.Toast;
import androidx.recyclerview.widget.RecyclerView;
import java.util.List;
public class MyRecyclerViewAdapter extends RecyclerView.Adapter<MyRecyclerViewAdapter.ViewHolder>
{
public List<String> mData, subdata, subdata2;
public LayoutInflater mInflater;
public ItemClickListener mClickListener;
public Context context;
public TextView myTextView, subtext;
public Button add;
public CheckBox done;
MyRecyclerViewAdapter(Context context, List<String> data, List<String> subdata, List<String> subdata2) {
this.mInflater = LayoutInflater.from(context);
this.mData = data;
this.subdata = subdata;
this.subdata2 = subdata2;
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = mInflater.inflate(R.layout.recyclerview_row, parent, false);
return new ViewHolder(view);
}
#Override
public void onBindViewHolder(ViewHolder holder, int position) {
String meta_data = mData.get(position);
String meta_subdata = subdata.get(position);
String meta_subdata2 = subdata2.get(position);
myTextView.setText(meta_data);
subtext.setText(meta_subdata +" "+ meta_subdata2);
add.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String[] item_param = myTextView.getText().toString().split(" ");
final Intent intent;
intent = new Intent(context, NewSLItem.class);
intent.putExtra("param",item_param[0]);
context.startActivity(intent);
}
});
}
#Override
public int getItemCount() {
return mData.size();
}
public class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener
{
public ViewHolder(View itemView)
{
super(itemView);
context = itemView.getContext();
myTextView = itemView.findViewById(R.id.tvAnimalName);
subtext = itemView.findViewById(R.id.subtext);
add = itemView.findViewById(R.id.add);
done =itemView.findViewById(R.id.done);
itemView.setOnClickListener(this);
}
#Override
public void onClick(View view)
{
if (mClickListener != null) mClickListener.onItemClick(view, getAdapterPosition());
}
}
String getItem(int id) {return mData.get(id);
}
void setClickListener(ItemClickListener itemClickListener) {
this.mClickListener = itemClickListener;
}
public interface ItemClickListener
{
void onItemClick(View view, int position);
}
}
and Here is the list class:
package com.example.homehandling;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.LinkedList;
import java.util.List;
import java.util.Locale;
import java.util.Map;
public class ToDoList extends AppCompatActivity implements MyRecyclerViewAdapter.ItemClickListener, View.OnClickListener {
public MyRecyclerViewAdapter adapter;
public Button btn;
public SharedPreferences sharedPreferences;
public SharedPreferences.Editor myEdit;
public LinkedList<String> items, remain_days, prio;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_shoppinglist);
sharedPreferences = getSharedPreferences("ToDoList", Context.MODE_PRIVATE);
myEdit = sharedPreferences.edit();
btn = findViewById(R.id.button);
items = new LinkedList<>();
remain_days = new LinkedList<>();
prio = new LinkedList<>();
RecyclerView recyclerView = findViewById(R.id.list);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
adapter = new MyRecyclerViewAdapter(this,items,remain_days,prio);
adapter.setClickListener(this);
recyclerView.setAdapter(adapter);
btn.setOnClickListener(this);
StartDisplay();
adapter.done.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(adapter.done.isChecked()) Toast.makeText(ToDoList.this,"Something is done",Toast.LENGTH_SHORT).show();
}
});
}
#Override
public void onItemClick(View view, int position) {
sharedPreferences = getSharedPreferences("ToDoList", Context.MODE_PRIVATE);
String item_click =adapter.getItem(position);
String[] itemarray = item_click.split(" ",0);
myEdit = sharedPreferences.edit();
myEdit.remove(itemarray[0]);
myEdit.commit();
adapter.notifyItemRemoved(position);
items.remove(item_click);
}
#Override
public void onClick(View v) {
Intent NewTLItem = new Intent(ToDoList.this, NewTLItem.class);
startActivity(NewTLItem);
}
#Override
public void onResume() {
super.onResume();
StartDisplay();
}
public void StartDisplay()
{
sharedPreferences = getSharedPreferences("ToDoList", Context.MODE_PRIVATE);
Map<String, ?> allEntries = sharedPreferences.getAll();
items.clear();
prio.clear();
remain_days.clear();
for (Map.Entry<String, ?> entry : allEntries.entrySet())
{
String key_word = entry.getKey();
String [] item_total = entry.getValue().toString().split(";");
if(key_word.contains("_")) key_word = key_word.replace("_"," ");
items.add(key_word);
remain_days.add(Long.toString(DateCalc(item_total[0])));
prio.add(item_total[1]);
}
adapter.notifyDataSetChanged();
}
public long DateCalc(String startdate)
{
Date system_date, due_date;
long diff_date = 0;
String currentDate = new SimpleDateFormat("dd-MM-yyyy", Locale.getDefault()).format(new Date());
SimpleDateFormat dates = new SimpleDateFormat("dd-MM-yyyy");
try {
system_date = dates.parse(currentDate);
due_date = dates.parse(startdate);
diff_date = (due_date.getTime()-system_date.getTime())/86400000;
} catch (ParseException e) {
e.printStackTrace();
}
return diff_date;
}
}
The first attemption was that the objects were declarated in the ViewHolder class, but I can not reach that from the list class.
I put the objects to the RecyclerView class and now I can reach thoose because for example the adapter.done.setOnClickListener() is valid from Android Studio point of view, but I always got null object reference. I think I know why, because the layout xml what the list class uses haven't got checkbox item, but then I don't know how can I solve this.
I also try to inflate the RecyclerView layout:
final View view = mInflater.inflate(R.layout.recyclerview_row,null);
...
...
...
adapter.done = view.findViewById(R.id.done);
but then I got LayoutInflater null object reference exception.

Why my arraylist size equal to 0 on the adapter page?

I started to wrote app that gets input from the user (in edittext) and after pressing button it should pass the valued to another activity in custom listview.
I found a problem during the debugging that the arraylist in the adapter getting null or 0.
Here is the Adapter code and main activity.
I hope someone could help me with this issue.
Adapter
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import androidx.recyclerview.widget.RecyclerView;
import java.util.ArrayList;
public class exampleAdapter extends RecyclerView.Adapter<exampleAdapter.ExampleViewHolder> {
private ArrayList<exampleItem> mExampleList;
public static class ExampleViewHolder extends RecyclerView.ViewHolder {
public TextView mTextViewLine1;
public TextView mTextViewLine2;
public ImageView imageView;
public ExampleViewHolder(View itemView) {
super(itemView);
mTextViewLine1 = itemView.findViewById(R.id.textview_line1);
mTextViewLine2 = itemView.findViewById(R.id.textview_line2);
imageView = itemView.findViewById(R.id.icond);
}
}
public exampleAdapter(ArrayList<exampleItem> exampleList) {
mExampleList = exampleList;
this.notifyDataSetChanged();
}
#Override
public ExampleViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.activity_example_item, parent, false);
ExampleViewHolder evh = new ExampleViewHolder(v);
return evh;
}
#Override
public void onBindViewHolder(ExampleViewHolder holder, int position) {
exampleItem currentItem = mExampleList.get(position);
holder.mTextViewLine1.setText(currentItem.getLine1());
holder.mTextViewLine2.setText(currentItem.getLine2());
if (currentItem.getLineimg().equalsIgnoreCase("s")) {
holder.imageView.setImageResource(R.drawable.salary);
}
if (currentItem.getLineimg().equalsIgnoreCase("e")){
holder.imageView.setImageResource(R.drawable.money);
}
}
#Override
public int getItemCount() {
return mExampleList.size();
}
}
MainActivity2
import androidx.appcompat.app.AppCompatActivity;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import java.lang.reflect.Type;
import java.util.ArrayList;
public class MainActivity2 extends AppCompatActivity {
private ArrayList<exampleItem> mExampleList = new ArrayList<>();
private exampleAdapter mAdapter = new exampleAdapter(mExampleList);
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main2);
setInsertButton();
loadData();
}
private void loadData() {
SharedPreferences sharedPreferences = getSharedPreferences("shared preferences4", MODE_PRIVATE);
Gson gson = new Gson();
String json = sharedPreferences.getString("task list4", null);
Type type = new TypeToken<ArrayList<exampleItem>>() {
}.getType();
mExampleList = gson.fromJson(json, type);
if (mExampleList == null) {
mExampleList = new ArrayList<>();
}
}
private void saveData() {
SharedPreferences sharedPreferences = getSharedPreferences("shared preferences4", MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
Gson gson = new Gson();
String json = gson.toJson(mExampleList);
editor.putString("task list4", json);
editor.apply();
}
private void setInsertButton() {
Button buttonInsert = findViewById(R.id.insert);
buttonInsert.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
final EditText line1 = findViewById(R.id.categ);
final EditText lineimg = findViewById(R.id.summ);
final EditText line2 = findViewById(R.id.date2);
String lin1 = line1.getText().toString();
String lin2 = line2.getText().toString();
String lin3 = lineimg.getText().toString();
insertItem(lin1, lin2, lin3);
saveData();
finish();
}
private void insertItem(String toString, String toString1, String toString2) {
mExampleList.add(new exampleItem(toString, toString2, toString1));
mAdapter.notifyItemInserted(mExampleList.size());
mAdapter.notifyDataSetChanged();
}
});
}
}
MainActivity
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import java.util.ArrayList;
public class MainActivity extends AppCompatActivity {
ArrayList<exampleItem> mExampleList = new ArrayList<>();
RecyclerView mRecyclerView;
private exampleAdapter mAdapter = new exampleAdapter(mExampleList);
private RecyclerView.LayoutManager mLayoutManager;
#Override
protected void onCreate(Bundle savedInstanceState1) {
super.onCreate(savedInstanceState1);
setContentView(R.layout.activity_main);
findViewById(R.id.buttoni).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(MainActivity.this,MainActivity2.class);
startActivity(intent);
}
});
buildRecyclerView();
}
private void buildRecyclerView() {
mRecyclerView = findViewById(R.id.recyclerview);
mRecyclerView.setHasFixedSize(true);
mLayoutManager = new LinearLayoutManager(this);
mAdapter = new exampleAdapter(mExampleList);
mRecyclerView.setLayoutManager(mLayoutManager);
mRecyclerView.setAdapter(mAdapter);
}
}
Bring out the inserItem method as separate from onClickListener and try out
private void insertItem(String toString, String toString1, String toString2) {
mExampleList.add(new exampleItem(toString, toString2, toString1));
mAdapter.notifyItemInserted(mExampleList.size());
mAdapter.notifyDataSetChanged();
}
you can remove this.notifydatachange() from adapter constructor
public exampleAdapter(ArrayList<exampleItem> exampleList) {
mExampleList = exampleList;
this.notifyDataSetChanged();
}

How can i display the message from receiver in an chat application in android studio?

We have programmed a chat application with Firebase in which the sender's messages are to be displayed on the right and those of the recipient on the left side.
The sender's messages are correctly displayed on the right side if you send the message with the Send button.
Unfortunately, the messages to the receiver are not shown on the left side.
Our Recyclerview java Code is this one:
package com.example.myapplicationsonet;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
public class Message_recyclerview extends AppCompatActivity {
TextView tvUsername;
ImageButton ibtnSend;
EditText etMessage;
FirebaseUser fuser;
DatabaseReference databaseReference;
MessageAdapter messageAdapter;
List<message_helperclass> mChat;
RecyclerView recyclerView;
Intent intent;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate( savedInstanceState );
setContentView( R.layout.activity_message_recyclerview );
recyclerView = (RecyclerView) findViewById(R.id.rvmessage);
recyclerView.setHasFixedSize(true);
LinearLayoutManager linearLayoutManager = new LinearLayoutManager(getApplicationContext());
linearLayoutManager.setStackFromEnd(true);
recyclerView.setLayoutManager(linearLayoutManager);
tvUsername = (TextView) findViewById(R.id.textView_message_username);
etMessage = (EditText) findViewById(R.id.messagebox);
ibtnSend = (ImageButton) findViewById(R.id.button_send);
intent = getIntent();
final String username = intent.getStringExtra("username");
fuser = FirebaseAuth.getInstance().getCurrentUser();
fuser = FirebaseAuth.getInstance().getCurrentUser();
databaseReference = FirebaseDatabase.getInstance().getReference("User").child(username);
databaseReference.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
tvUsername.setText(username);
readMessages(fuser.getUid(), username);
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
ibtnSend.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String msg = etMessage.getText().toString();
if (!msg.equals("")){
sendMessage(fuser.getUid(), username, msg);
}else {
Toast.makeText(Message_recyclerview.this, "Du kannst keine leeren Nachrichten versenden", Toast.LENGTH_LONG).show();
}
etMessage.setText("");
}
});
}
private void sendMessage(String sender, String receiver, String message ){
DatabaseReference databaseReference = FirebaseDatabase.getInstance().getReference();
HashMap<String, Object> hashMap = new HashMap<>();
hashMap.put("sender", sender);
hashMap.put("receiver", receiver);
hashMap.put("message", message);
databaseReference.child("Chats").push().setValue(hashMap);
}
private void readMessages(final String myid, final String username){
mChat = new ArrayList<>();
databaseReference = FirebaseDatabase.getInstance().getReference("Chats");
databaseReference.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
mChat.clear();
for (DataSnapshot snapshot : dataSnapshot.getChildren()){
message_helperclass chat = snapshot.getValue(message_helperclass.class);
if (chat.getReceiver().equals(myid) && chat.getSender().equals(username) ||
chat.getReceiver().equals(username) && chat.getSender().equals(myid)){
mChat.add(chat);
}
messageAdapter = new MessageAdapter(Message_recyclerview.this, mChat);
recyclerView.setAdapter(messageAdapter);
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
}
And this is our Adapter Class:
package com.example.myapplicationsonet;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
import java.util.List;
public class MessageAdapter extends RecyclerView.Adapter<MessageAdapter.ViewHolder> {
public static final int MSG_TYPE_LEFT = 0;
public static final int MSG_TYPE_RIGHT = 1;
private Context mContext;
private List<message_helperclass> mChat;
FirebaseUser fUser;
public MessageAdapter(Context mContext, List<message_helperclass> mChat){
this.mChat = mChat;
this.mContext = mContext;
}
#NonNull
#Override
public MessageAdapter.ViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
if (viewType == MSG_TYPE_RIGHT){
View view = LayoutInflater.from(mContext).inflate(R.layout.chat_item_right, parent, false);
return new MessageAdapter.ViewHolder(view);
} else {
View view = LayoutInflater.from(mContext).inflate(R.layout.chat_item_left, parent, false);
return new MessageAdapter.ViewHolder(view);
}
}
#Override
public void onBindViewHolder(#NonNull ViewHolder holder, int position) {
message_helperclass chat = mChat.get(position);
holder.show_message.setText(chat.getMessage());
}
#Override
public int getItemCount() {
return mChat.size();
}
public class ViewHolder extends RecyclerView.ViewHolder {
public TextView show_message;
public ViewHolder(#NonNull View itemView) {
super(itemView);
show_message = itemView.findViewById(R.id.show_message);
}
}
#Override
public int getItemViewType(int position) {
fUser = FirebaseAuth.getInstance().getCurrentUser();
if (mChat.get(position).getSender().equals(fUser.getUid())){
return MSG_TYPE_RIGHT;
} else {
return MSG_TYPE_LEFT;
}
}
}
Unfortunately, we cannot find the error why the recipient messages are not displayed on the left.
I hope you can help us. It would be important.
Thanks!
Can't Comment, but have you checked your chat_item_right and chat_item_left XML file? Your code appears right so the error might be there.

Xml is working fine but json is not in jax rs

I am learning restful api with jax rs(jersey) and I making a messageResource class in which I am getting messages .everything works fine with xml but get function is not working with json .I have tried content type and accept headers too but its not working and returning 500 error and content type text/html.
Even the maven dependency moxy is also set in pom.xml
Can anybody help me finding the error.
package org.restfulapi.messenger.resources;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.ArrayList;
import java.util.List;
import javax.ws.rs.Consumes;
import javax.ws.rs.DELETE;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.PUT;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.QueryParam;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.Response.Status;
import javax.ws.rs.core.UriInfo;
import org.restfulapi.messenger.services.DataNotFoundException;
import org.restfulapi.messenger.services.Link;
import org.restfulapi.messenger.services.Message;
import org.restfulapi.messenger.services.MessageService;
#Path("messages")
#Produces(value= {MediaType.APPLICATION_JSON,MediaType.APPLICATION_XML})
#Consumes(value= {MediaType.APPLICATION_JSON,MediaType.APPLICATION_XML})
public class MessageResource
{
MessageService service=new MessageService();
#GET
#Path("/{messageID}")
public Message getMessage(#PathParam("messageID")int id,#Context UriInfo uriinfo )
{
Message msg=service.getMessage(id);
if(service.getMessage(id)==null)
{
throw new DataNotFoundException("message with id "+id+"not found");
}
return msg;
}
#GET
public List<Message> getMessages(#QueryParam("year")int year,
#QueryParam("start") int start,
#QueryParam("size") int size)
{
if(year>0)
{
return service.getbyyear(year);
}
if(start>0 & size>0)
{
return service.get(start, size);
}
return service.getMessages();
}
#POST
public Response addMessage(Message msg) throws URISyntaxException
{
return Response.created(new URI("/messenger/webapi/messages"+msg.getId())).entity(service.addMessage(msg)).build();
}
package org.restfulapi.messenger.services;
import java.util.List;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.HashMap;
import java.util.Map;
public class MessageService {
private HashMap<Integer, Message> messages = Database.getMessages();
public MessageService()
{
}
public ArrayList<Message> getMessages() {
return new ArrayList<Message>(messages.values());
}
;
public Message getMessage(int id) {
return messages.get(id);
}
public ArrayList<Message> getbyyear(int year)
{
ArrayList<Message> result =new ArrayList();
Calendar cal=Calendar.getInstance();
for(Message msg:messages.values())
{
cal.setTime(msg.getCreated());
if(cal.get(Calendar.YEAR)==year)
result.add(msg);
}
return result;
}
public List<Message> get(int start,int size)
{
ArrayList<Message> result =new ArrayList<Message>(messages.values());
return result.subList(start, start+size);
}
public Message addMessage(Message message) {
message.setId(messages.size() + 1);
messages.put(message.getId(), message);
return message;
}
}
package org.restfulapi.messenger.services;
import java.util.ArrayList;
import java.util.Date;
import javax.xml.bind.annotation.XmlRootElement;
#XmlRootElement
public class Message {
private int id;
private String msg;
private Date created;
private String author;
private ArrayList<Link> links=new ArrayList();
public ArrayList<Link> getLinks() {
return links;
}
public void setLinks(ArrayList<Link> links) {
this.links = links;
}
public Message()
{
}
public Message(int id, String msg, String author) {
this.id = id;
this.msg = msg;
this.author = author;
this.created = new Date();
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getMsg() {
return msg;
}
public void setMsg(String msg) {
this.msg = msg;
}
public Date getCreated() {
return created;
}
public void setCreated(Date created) {
this.created = created;
}
public String getAuthor() {
return author;
}
public void setAuthor(String author) {
this.author = author;
}
public void addLink(String uri, String rel) {
Link l=new Link(uri,rel);
links.add(l);
}
}
public class Database
{
private static HashMap<Integer,Message> messages=new HashMap();
public static HashMap<Integer,Message> getMessages()
{
return messages;
}
}

How to format SimpleIntegerProperty output

I do have a SimpleIntegerProperty which contains a number which is the time in 100ms steps like 40 is 4,0 seconds
I do want to display this value to the user with a Label which should display "4,0 s"
I would like to bind the value with the bindings api like
label.textProperty().bind(myobject.secondsProperty().asString());
but how do i create a simple and reusable Converter, i do need only the unidirectional binding.
There is an overloaded form of the asString(...) method that takes a format string as an argument:
String secondsFormat = "%.1f s" ;
label.textProperty().bind(myobject.secondsProperty().asString(secondsFormat));
If you really need a StringConverter, you can do
StringConverter<Integer> deciSecondsConverter = new StringConverter<Integer>() {
#Override
public String toString(Integer deciSeconds) {
return String.format("%.1f s", deciSeconds.doubleValue()/10);
}
#Override
public Integer fromString(String string) {
// not implemented
return null ;
}
};
and then
label.textProperty().bind(Bindings.createStringBinding(
() -> deciSecondsConverter.toString(myobject.getSeconds()),
myobject.secondsProperty()
));
SSCCE:
import javafx.animation.AnimationTimer;
import javafx.application.Application;
import javafx.beans.binding.Bindings;
import javafx.beans.property.IntegerProperty;
import javafx.beans.property.SimpleIntegerProperty;
import javafx.geometry.Insets;
import javafx.scene.Scene;
import javafx.scene.control.Label;
import javafx.stage.Stage;
import javafx.util.StringConverter;
public class StopwatchTest extends Application {
#Override
public void start(Stage primaryStage) {
IntegerProperty tenthsOfSeconds = new SimpleIntegerProperty();
Label label = new Label();
StringConverter<Integer> deciSecondsConverter = new StringConverter<Integer>() {
#Override
public String toString(Integer deciSeconds) {
return String.format("%.1f s", deciSeconds.doubleValue()/10);
}
#Override
public Integer fromString(String string) {
// not implemented
return null ;
}
};
label.textProperty().bind(Bindings.createStringBinding(() ->
deciSecondsConverter.toString(tenthsOfSeconds.get()),
tenthsOfSeconds));
new AnimationTimer() {
#Override
public void handle(long now) {
tenthsOfSeconds.set((int)System.currentTimeMillis() % 60000 / 100);
}
}.start();
label.setPadding(new Insets(5, 20, 5, 20));
primaryStage.setScene(new Scene(label, 80, 30));
primaryStage.show();
}
public static void main(String[] args) {
launch(args);
}
}