Android Studio saving data in database - java

I'm new here, and also new to Android Studio.
My first project is to create a diary to save a users workouts.
I'm having trouble saving for this data..
Here is my front page for the app. With the button "Styrkeboken" (Strengthbook) I'll be entering my sets, reps, weight(vikt) and excercise(övning). I want to save this data in the second button "Historik" (History), but I can't manage it to work as I want to..
Code from my class "Pass" (Workout):
package com.example.mama0086.styrkeboken;
public class Pass {
private int _set;
private int _reps;
private float _vikt;
private String _övning;
public Pass() {
}
public Pass(int set, int reps, float vikt, String övning) {
this._set = set;
this._reps = reps;
this._vikt = vikt; //Vikt = weight
this._övning = övning; //Övning = excercise
}
public void set_set(int _set) {
this._set = _set;
}
public void set_reps(int _reps) {
this._reps = _reps;
}
public void set_vikt(float _vikt) {
this._vikt = _vikt;
}
public void set_övning(String _övning) {
this._övning = _övning;
}
public int get_set() {
return _set;
}
public int get_reps() {
return _reps;
}
public float get_vikt() {
return _vikt;
}
public String get_övning() {
return _övning;
}
}
Code from my class "Historik" (History):
public class Historik extends AppCompatActivity {
EditText editSet;
TextView textSet;
EditText editReps;
TextView textReps;
EditText editVikt;
TextView textVikt;
EditText editÖvning;
TextView textÖvning;
MyDBHandler dbHandler;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_historik);
editSet = (EditText) findViewById(R.id.editSet);
textSet = (TextView) findViewById(R.id.textSet);
editReps = (EditText) findViewById(R.id.editReps);
textReps = (TextView) findViewById(R.id.textReps);
editVikt = (EditText) findViewById(R.id.editVikt);
textVikt = (TextView) findViewById(R.id.textVikt);
editÖvning = (EditText) findViewById(R.id.editÖvning);
textÖvning = (TextView) findViewById(R.id.textÖvning);
dbHandler = new MyDBHandler(this, null, null, 1);
printDatabase();
}
//Add excercise
public void addBtn(View view){
Pass pass = new Pass(textSet.getText().toString()); //Pass is swedish for work-out
dbHandler.addPass(pass);
printDatabase();
}
public void removeBtn(){
String inputText = textSet.getText().toString();
dbHandler.deletePass(inputText);
printDatabase();
}
public void printDatabase(){
String dbString = dbHandler.historikToString();
textSet.setText(dbString);
editSet.setText("");
textReps.setText(dbString);
editReps.setText("");
textVikt.setText(dbString);
editVikt.setText("");
textÖvning.setText(dbString);
editÖvning.setText("");
}
}
In the "Historik" class I get this error message:
"Cannot resolve constructor 'Pass(java.lang.String)'
please let me know if you need the code for my database.
I appreciate the help!

You defined 2 different constructors for your Pass class :
public Pass() {
}
public Pass(int set, int reps, float vikt, String övning) {
this._set = set;
this._reps = reps;
this._vikt = vikt; //Vikt = weight
this._övning = övning; //Övning = excercise
}
However in your Historik activity, you're trying to instantiate a new Pass with a String only as a parameter Pass pass = new Pass(textSet.getText().toString());
You will need to change this line to match one of the 2 constructors you have, or define a 3rd one taking only a String as argument
EDIT : Depending on your Pass object, you can either :
declare a 3rd constructor taking only a String (I assume it's övning)
public Pass(String övning) {
this._övning = övning;
}
if the textSet.getText().toString() is not relevant, simply use the default constructor Pass pass = new Pass();

Related

Edit values and update in firebase

this time i want to edit and update the new values in Firebase Database. I have read the firebase documentation and followed the steps. https://firebase.google.com/docs/database/android/read-and-write#update_specific_fields
i need a litte orientation, following the documentation's steps i have modifed my POJO class,
as proof just add the interno key in the public Map<>...
public class Cow implements Serializable {
String interno;
public Cow() {
}
public Cow(String interno) {
this.interno = interno;
}
public String getInterno() {
return interno;
}
public void setInterno(String interno) {
this.interno = interno;
}
#Exclude
public Map<String, Object> toMap() {
HashMap<String, Object> result = new HashMap<>();
result.put("inte", interno);
return result;
}
}
This is my database in firebase
I have a recyclerview and I send the values to another activity by an intent, where i show the details, in this detailcow i want to modify the values.
This is the code:
public class Cowdetail extends AppCompatActivity {
DatabaseReference reference;
EditText tvinterno, tvsiniiga, tvpadre, tvmadre, tvnacimiento, tvinseminacion, tvtoro, tvestatus, tvnotas;
AppCompatImageView tvimage;
Button tvbutton;
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.detailcow);
tvinterno = (EditText) findViewById(R.id.tvinterno);
tvsiniiga = (EditText) findViewById(R.id.tvsiniiga);
tvpadre = (EditText) findViewById(R.id.tvpadre);
tvmadre = (EditText) findViewById(R.id.tvmadre);
tvnacimiento = (EditText) findViewById(R.id.tvnacimiento);
tvinseminacion = (EditText) findViewById(R.id.tvinsemincion);
tvtoro = (EditText) findViewById(R.id.tvtoro);
tvestatus = (EditText) findViewById(R.id.tvestatus);
tvnotas = (EditText) findViewById(R.id.tvnotas);
tvimage = (AppCompatImageView) findViewById(R.id.tvimage);
tvbutton = findViewById(R.id.actualizar);
String vpadre = "";
String vmadre = "";
String vinterno = "";
String vsiniiga = "";
String vnacimiento = "";
String vinseminacion = "";
String vtoro = "";
String vestatus = "";
String vnotas = "";
String vurl;
Bundle extras = getIntent().getExtras();
if (extras !=null);
vinterno = extras.getString("keyint");
vsiniiga = extras.getString("keysin");
vmadre = extras.getString("madre");
vpadre = extras.getString("padre");
vnacimiento = extras.getString("nacimiento");
vinseminacion = extras.getString("inseminacion");
vtoro = extras.getString("toro");
vestatus = extras.getString("estatus");
vnotas = extras.getString("notas");
String image = extras.getString("img");
if (image == null|| image.isEmpty()){
tvimage.setImageResource(R.drawable.ic_imageinf);
} else {
Picasso.get().load(image).fit().centerCrop().into(tvimage);
}
tvpadre.setText(vpadre);
tvinterno.setText(vinterno);
tvsiniiga.setText(vsiniiga);
tvmadre.setText(vmadre);
tvnacimiento.setText(vnacimiento);
tvinseminacion.setText(vinseminacion);
tvtoro.setText(vtoro);
tvestatus.setText(vestatus);
tvnotas.setText(vnotas);
tvbutton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Update();
}
});
}
private void Update() {
DatabaseReference ref = FirebaseDatabase.getInstance().getReference().child("Vacas");
Map<String, Object> updates = new HashMap<String, Object>();
updates.put("inte", tvinterno);
ref.updateChildren(updates);
}
}
I have added a button to the layout, it has to save the edited values to firebase with the public void Update, Im doing something wrong, but in my short (almost nil) experience i can't see the error. also, i'm looking for a asesor who can guide me in my project, if someone want to talk about it, send me an email to: pjcm97#outlook.com
Firebase Realtime Database stores JSON data. You're trying to write an EditText object to it, which is not JSON data. So your code is most likely crashing.
private void Update() {
DatabaseReference ref = FirebaseDatabase.getInstance().getReference().child("Vacas");
Map<String, Object> updates = new HashMap<String, Object>();
updates.put("inte", tvinterno.getText().toString());
ref.updateChildren(updates);
}
I also highly recommend always checking the result of a write operation, to see if it succeeded, as shown in the documentation on adding a completion listener.

How to generate a TextView on AsyncTask and place it on a GridLayout?

This is my situation:
I have a GridLayout (wich has some textviews in some cells of it right at the begining of the activity, but i will change it to generate those textviews dynamically later) and I want to place some textViews in a few cells of it.
The problem: I don't know how many textViews I will need. It depends of the information of the database. Besides, I don't know how to add the textViews generated to the gridLayout from an AsyncTask.
So, i've been looking for some answers but I couldn't make it work. I tried something like this, but is not exactly what i'm looking for (i create a new TextView, but can't add it to the gridLayout from that thread).
This is the workflow of my app:
1º I start the activity with the gridLayout. It has some textViews:
This is the main Activity:
public class MostrarProyectos extends AppCompatActivity {
private final String TAG = "MostrarProyectos";
//Para obtener de un hilo no principal los proyectos:
public static ArrayList<Proyecto> listaDeProyectos = new ArrayList<>();
public GridLayout grid;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_mostrar_proyectos);
grid = (GridLayout) findViewById(R.id.grid);
EstrategiaObtenerObjetoDB e = FabricaEstrategiaObtenerDB.getInstance().construirEstrategia("proyecto", this); //This is a Fabric, wich obtains a Strategy
e.execute(this.getApplicationContext(), "proyecto", this, this.grid);//I sended a lot of things to test if something gives result
}
}
2º In that main class, I started a new Thread with AsyncTask, to get data from a SQLite DB.
This is the Fabric:
public class FabricaEstrategiaObtenerDB {
private static final FabricaEstrategiaObtenerDB ourInstance = new FabricaEstrategiaObtenerDB();
public static FabricaEstrategiaObtenerDB getInstance() {
return ourInstance;
}
private FabricaEstrategiaObtenerDB() {}
public EstrategiaObtenerObjetoDB construirEstrategia(String tabla, Activity acti){
switch(tabla){
//Some other cases
case "proyecto":
EstrategiaObtenerObjetoDBProyecto p = new EstrategiaObtenerObjetoDBProyecto(acti, new onTextViewCreatedListener() {
#Override
public void onTextViewCreated(TextView tv) {
//I don't know what to do here
}
}); //This code I tried from the other stackOverflow answer
return p;
default:
return null;
}
}
}
This an abstract class to obtain objects from the DB:
public abstract class EstrategiaObtenerObjetoDB extends AsyncTask<Object, Void, ArrayList<Object>> {
protected onTextViewCreatedListener onTextViewCreatedListener; //part of the code from the other StackOverflow user.
Activity miActividad;
public EstrategiaObtenerObjetoDB(Activity act, onTextViewCreatedListener onTextViewCreatedListener){
this.onTextViewCreatedListener = onTextViewCreatedListener; //This is too code from the other user.
this.miActividad = act;
}
#Override
protected ArrayList<Object> doInBackground(Object... params) {
AppDbHelper mDbHelper = new AppDbHelper(miActividad.getApplicationContext());
SQLiteDatabase db = mDbHelper.getReadableDatabase();
String[] projection = obtenerSelect();
Cursor c = armarQuery(db, (String)params[1], projection); //params[1] is the name of the table in the DB
ArrayList<Object> arrayDeObjetos = new ArrayList<>();
try{
arrayDeObjetos.add(miActividad.getApplicationContext());//add the context
arrayDeObjetos.add(miActividad.findViewById(R.id.grid));//add the grid
armarObjetos(c);
return arrayDeObjetos;
}catch (Exception e){
String b = e.getMessage();
return null;
}
}
#Override
protected abstract void onPostExecute(ArrayList<Object> objects);
protected abstract String[] obtenerSelect();
protected abstract Cursor armarQuery(SQLiteDatabase db, String tabla, String[] projection);
protected abstract void armarObjetos(Cursor c);
}
And this is the specific Strategy:
public class EstrategiaObtenerObjetoDBProyecto extends EstrategiaObtenerObjetoDB {
public EstrategiaObtenerObjetoDBProyecto(Activity act,onTextViewCreatedListener onTextViewCreatedListener) {
super(act,onTextViewCreatedListener);
}
#Override
protected String[] obtenerSelect() {
String[] projection = {
AppContract.Proyecto._ID,
AppContract.Proyecto.COLUMN_NOMBRE,
AppContract.Proyecto.COLUMN_DESCRIPCION,
AppContract.Proyecto.COLUMN_PRIORIDAD,
AppContract.Proyecto.COLUMN_ANIO,
AppContract.Proyecto.COLUMN_MES,
AppContract.Proyecto.COLUMN_SEMANA,
AppContract.Proyecto.COLUMN_DURACION,
};
return projection;
}
#Override
protected Cursor armarQuery(SQLiteDatabase db, String tabla, String[] projection) {
Cursor cursor = db.query(
tabla,
projection,
null,
null,
null,
null,
null
);
return cursor;
}
#Override
protected void armarObjetos(Cursor c) {
c.moveToFirst();
ArrayList<Object> proyectos = new ArrayList<>();
do {
try{
String nombre = c.getString(c.getColumnIndex(AppContract.Proyecto.COLUMN_NOMBRE));
String descripcion = c.getString(c.getColumnIndex(AppContract.Proyecto.COLUMN_DESCRIPCION));
String prioridad = c.getString(c.getColumnIndex(AppContract.Proyecto.COLUMN_PRIORIDAD));
String anio = c.getString(c.getColumnIndex(AppContract.Proyecto.COLUMN_ANIO));
String mes = c.getString(c.getColumnIndex(AppContract.Proyecto.COLUMN_MES));
String semana = c.getString(c.getColumnIndex(AppContract.Proyecto.COLUMN_SEMANA));
String duracion = c.getString(c.getColumnIndex(AppContract.Proyecto.COLUMN_DURACION));
Proyecto p = new Proyecto(nombre,descripcion, prioridad, anio, mes, semana, duracion);
MostrarProyectos.listaDeProyectos.add(p);
proyectos.add(p);
}catch(Exception e){
Log.d("EstrategiaObtenerPr",e.getMessage());
}
} while (c.moveToNext());
}
#Override
protected void onPostExecute(ArrayList<Object> objects) {
MostrarProyectos.listaDeProyectos.add((Proyecto)objects.get(i));
GridLayout grid = (GridLayout) miActividad.findViewById(R.id.grid);
if(!MostrarProyectos.listaDeProyectos.isEmpty()){
for(int numeroTemporal = 0; numeroTemporal<MostrarProyectos.listaDeProyectos.size();numeroTemporal++){
Proyecto j = MostrarProyectos.listaDeProyectos.get(numeroTemporal);
TextView text = new TextView(miActividad.getApplicationContext());
text.setText(j.getNombre());
int numFila = MostrarProyectos.contarFilas(j.getMes(), j.getSemana());
GridLayout.LayoutParams params3 = new GridLayout.LayoutParams();
params3.rowSpec = GridLayout.spec(numFila);//,Integer.parseInt(j.getDuracion())
Log.d("MostrarProyecto", numFila+","+Integer.parseInt(j.getDuracion()));
params3.columnSpec = GridLayout.spec(3);
text.setLayoutParams(params3);
try{
if(onTextViewCreatedListener!=null){
onTextViewCreatedListener.onTextViewCreated(text);//from the other user
}
}catch (Exception excepcion){
Log.d("MostrarProyecto", excepcion.getMessage());
}
}
}
else{
Toast.makeText(miActividad.getApplicationContext(),"No hay proyectos",Toast.LENGTH_LONG);
}
MostrarProyectos.terminoCargaDatos = true;
}
}
3º After I get the data, I want to generate as many TextViews as objects i've got from the DB, so I use a 'for' to see how many objects i have inside a temporal list i created. For heach object, I want to create a TextView, and add it to the gridLayout (that is on the main thread).
And finally, an interface from the other answer:
public interface onTextViewCreatedListener {
public void onTextViewCreated(TextView tv);
}
I hope you can help me. Thank you.
EDIT_1: I need to use other thread different from the UI thread because i need to search in the DB the data.
You have to split your logic, search data in the DB in AsyncTask or simple new Thread() and then create UI elements and attach them in UI thread.
mActivity
.runOnUiThread(
new Runnable() {
#Override
public void run() {
//create a TextView, and add it to the gridLayout
}
});

How do I access an ArrayList with user input using 2 classes?

I have an object class called "Services" as shown below...
public class Services {
private ArrayList<Double> costDATA = new ArrayList<>();
private ArrayList<Double> costWLAN = new ArrayList<>();
private ArrayList<Double> costUTILITY = new ArrayList<>();
private ArrayList<String> dimensions = new ArrayList<>();
private ArrayList<String> serviceNames = new ArrayList<>();
private double solution;
private double battery;
public void addServiceName(String services) {
this.serviceNames.add(services);
}
public void addDimensions(String services) {
this.dimensions.add(services);
}
public int getDimensionSize(){
return dimensions.size();
}
public void addDataCost(double dataCost){
costDATA.add(dataCost);
}
public void addWlanCost(double wlanCost){
costWLAN.add(wlanCost);
}
public void addUtilityCost(double utilityCost){
costUTILITY.add(utilityCost);
}
public void setSolution(double solution){
this.solution = solution;
}
public double getSolution(){
return solution;
}
public void setBattery(double battery){
this.battery = battery;
}
public double getBattery() {
return battery;
}
public ArrayList<Double> getCostDATA() {
return costDATA;
}
public ArrayList<Double> getCostWLAN() {
return costWLAN;
}
public ArrayList<Double> getCostUTILITY() {
return costUTILITY;
}
public ArrayList<String> getServiceNames() {
return serviceNames;
}
}
I use this class to store user input data from the MainActivity of my UI. Here is my MainActivity.
public class MainActivity extends AppCompatActivity {
//declare variables
private EditText name;
private EditText data;
private EditText wlan;
private EditText utility;
private Button addservice;
ListView lv;
ListView lv2;
ListView lv3;
ListView lv4;
Services services = new Services();
public ArrayList<String> servicenames;
public ArrayList<String> dimensions;
private ArrayAdapter<String> namesAdapter;
private ArrayAdapter<Double> dataAdapter;
private ArrayAdapter<Double> wlanAdapter;
private ArrayAdapter<Double> utilityAdapter;
private ArrayList<Double> costDATA;
private ArrayList<Double> costWLAN;
private ArrayList<Double> costUTILITY;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//map the components to the variables
name = (EditText) findViewById(R.id.servicename);
data = (EditText) findViewById(R.id.data);
wlan = (EditText) findViewById(R.id.wlan);
utility = (EditText) findViewById(R.id.utility);
addservice = (Button) findViewById(R.id.addservice);
lv = (ListView) findViewById(R.id.lv);
lv2 = (ListView) findViewById(R.id.lv2);
lv3 = (ListView) findViewById(R.id.lv3);
lv4 = (ListView) findViewById(R.id.lv4);
//create arraylists for each component
servicenames = services.getServiceNames();
costDATA = services.getCostDATA();
costWLAN = services.getCostWLAN();
costUTILITY = services.getCostUTILITY();
//create adapters to pass on the arraylist
namesAdapter = new ArrayAdapter<>(MainActivity.this, android.R.layout.simple_list_item_1, servicenames);
dataAdapter = new ArrayAdapter<>(MainActivity.this, android.R.layout.simple_list_item_1, costDATA);
wlanAdapter = new ArrayAdapter<>(MainActivity.this, android.R.layout.simple_list_item_1, costWLAN);
utilityAdapter = new ArrayAdapter<>(MainActivity.this, android.R.layout.simple_list_item_1, costUTILITY);
//display each arraylist in the listviews
lv.setAdapter(namesAdapter);
lv2.setAdapter(wlanAdapter);
lv3.setAdapter(dataAdapter);
lv4.setAdapter(utilityAdapter);
services.addDimensions("DATA");
services.addDimensions("WLAN");
onClickBtn();
}
public void onClickBtn() { //when user clicks button, the user input is added to the listview, and cleared for the next service
addservice.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String namesOfService = name.getText().toString(); //user input for service names
String costOfData = data.getText().toString(); //user input for data costs
String costOfWLAN = wlan.getText().toString(); //user input for wlan costs
String costOfUtility = utility.getText().toString(); //user input for utility costs
double doubleWLAN = Double.parseDouble(costOfWLAN); //convert user input into double
double doubleData = Double.parseDouble(costOfData);
double doubleUtility = Double.parseDouble(costOfUtility);
//costDATA.add(doubleData); //add the double costs to each resource arraylist
//costWLAN.add(doubleWLAN);
//costUTILITY.add(doubleUtility);
services.addDataCost(doubleData);
services.addWlanCost(doubleWLAN);
services.addUtilityCost(doubleUtility);
services.addDimensions(namesOfService);
services.addServiceName(namesOfService);
namesAdapter.notifyDataSetChanged();
dataAdapter.notifyDataSetChanged();
wlanAdapter.notifyDataSetChanged();
utilityAdapter.notifyDataSetChanged();
name.setText(""); //empty the edit text fields when button is clicked
wlan.setText("");
data.setText("");
utility.setText("");
}
});
}
public void nextButton(View view) //next button, onto the next activity
{
Intent intent = new Intent(MainActivity.this, ParticleActivity.class);
startActivity(intent);
}
Now my mainActivity works fine, the UI displays the user input costs and service names just the way I need it to. After this is done, the user then goes to an activity called "ParticleActivity" which then executes two other java classes called "CustomUseCase" and "CustomService". In my "CustomUseCase" class, I always get nullpointerexception and it states that my arrayLists are empty. What am I doing wrong here? I am trying to access the arraylist from the services object as that is where I thought the values will be stored?
public class CustomServiceSelection implements Goodness {
Services services;
private ArrayList<Double> costData = services.getCostDATA();
private ArrayList<Double> costWlan = services.getCostWLAN();
private ArrayList<Double> costUtilities = services.getCostUTILITY();
private double batteryCost = services.getBattery();
public CustomServiceSelection(double costOfBattery, ArrayList<Double> costOfData, ArrayList<Double> costOfWlan,
ArrayList<Double> costOfUtilities) {
if (costUtilities == null || costUtilities.size() < 1 || costData.size() < 1 || costWlan.size() < 1) {
throw new RuntimeException("Please add atleast 1 cost to Data, WLAN and Utility");
}
if (batteryCost < 1) {
throw new RuntimeException("Please enter a battery cost more than 1");
}
this.batteryCost = costOfBattery;
this.costData = costOfData;
this.costWlan = costOfWlan;
this.costUtilities = costOfUtilities;
}
You get a nullpointerexception because you are trying to immediately access an unassigned variable
Services services; // null
// These are all null references
private ArrayList<Double> costData = services.getCostDATA();
private ArrayList<Double> costWlan = services.getCostWLAN();
private ArrayList<Double> costUtilities = services.getCostUTILITY();
private double batteryCost = services.getBattery();
You need to pass some initialized instance of the Services class into a constructor of CustomServiceSelection, then initialize the lists and other things

How to reload recyclerview row without position of the list?

I have an ArrayList of a custom object. This ArrayList I pass to my RecyclerView Adapter. When an event occurs I need to retrieve the object from the ArrayList that contains a variable with a unique value, make changes to that object and then reload the ViewHolder corresponding to that object. How do I achieve this?
The problem is that I don't have the position of the object within the ArrayList because the positions keep changing dynamically. I just have this unique value corresponding to a object on the basis of which I want to make changes.
I tried doing list.clear() then reassigning objects to the ArrayList with the updated values and then calling adapter.notifyDataSetChanged() but it didn't work.
EDIT:
I have provided the code below of the Activity which contains the recyclerview. The actual code is much larger so I decided to edit it to only show the necessary details regarding this question. Please let me know if I need to add more code.
So, basically what happens here is that IMActivity is bound to a service and passes its context to the service while binding. When an event occurs in the service a database value is changed and updateActivity() is called in the service.
What I want updateActivity() to do is to check the chatMsgList for a ChatMsg object that contains a variable that has a unique value and reload the viewholder corresponding to that ChatMsg object.
Please let me know if I need to clarify further.
public class IMActivity extends AppCompatActivity implements Sertivity {
private RecyclerView recyclerView;
private ImAdapter imAdapter;
private List<ChatMsg> chatMsgList = new ArrayList<>();
EditText etIM;
ImageButton ibSend;
TalkSeeService.TalkSeeBinder talkSeeBinder;
String usernames[]= new String[10];
String otherUserName;
List<Msg> msgList;
DBAct db;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
bindService(new Intent(com.abdralabs.talksee.IMActivity.this, TalkSeeService.class), new ServiceConnection() {
#Override
public void onServiceConnected(ComponentName name, IBinder service) {
talkSeeBinder = (TalkSeeService.TalkSeeBinder)service;
talkSeeBinder.setSertivity(com.abdralabs.talksee.IMActivity.this);
}
#Override
public void onServiceDisconnected(ComponentName name) {
talkSeeBinder.setSertivity(null);
talkSeeBinder = null;
}
},BIND_AUTO_CREATE);
setContentView(R.layout.activity_im);
recyclerView = (RecyclerView)findViewById(R.id.rv_im);
imAdapter = new ImAdapter(chatMsgList);
LinearLayoutManager layoutManager = new LinearLayoutManager(getApplicationContext());
layoutManager.setStackFromEnd(true);
recyclerView.setLayoutManager(layoutManager);
recyclerView.setAdapter(imAdapter);
ibSend = (ImageButton)findViewById(R.id.ib_send);
etIM = (EditText)findViewById(R.id.et_im);
ibSend.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//THE TEXT FROM THE EDITTEXT IS TAKEN AND THEN ADDED TO THE DATABASE
updateChatData();
}
});
db = new DBAct(com.abdralabs.talksee.IMActivity.this,otherUserName);
msgList = db.getAllMessages();
db.close();
prepareChatData();
}
private void prepareChatData() {
for (int i=0; i<msgList.size(); i++) {
ChatMsg chatMsg = new ChatMsg(msgList.get(i).getMessage(),
convertToDayDateTime(Long.valueOf(msgList.get(i).getTime())),
msgList.get(i).getOther(),
getReceiptFromDelivered(i));
chatMsgList.add(chatMsg);
}
imAdapter.notifyDataSetChanged();
}
private void updateChatData(){
msgList = db.getAllMessages();
db.close();
int i = msgList.size() - 1;
ChatMsg chatMsg = new ChatMsg(msgList.get(i).getMessage(),
convertToDayDateTime(Long.valueOf(msgList.get(i).getTime())),
msgList.get(i).getOther(),
getReceiptFromDelivered(i));
chatMsgList.add(chatMsg);
imAdapter.notifyDataSetChanged();
recyclerView.smoothScrollToPosition(imAdapter.getItemCount());
}
#Override
public void updateActivity() {
chatMsgList.clear();
prepareChatData();
recyclerView.smoothScrollToPosition(imAdapter.getItemCount());
}
#Override
public void callActivityMethod() {
updateChatData();
}
private String convertToDayDateTime(long timestamp){
Calendar cal = Calendar.getInstance();
TimeZone tz = cal.getTimeZone();
SimpleDateFormat sdf = new SimpleDateFormat("EEE dd/MM/yyyy HH:mm");
sdf.setTimeZone(tz);
String localTime = sdf.format(new Date(timestamp));
return localTime;
}
private String getReceiptFromDelivered(int position){
String receipt;
if (msgList.get(position).getDelivered().equals("0")){
receipt = "...";
}else {
receipt = "S";
}
return receipt;
}
}
IMAdapter.java
public class ImAdapter extends RecyclerView.Adapter <RecyclerView.ViewHolder> {
private List<ChatMsg> chatMsgList = new ArrayList<ChatMsg>();
final int VIEW_TYPE_USER = 1;
final int VIEW_TYPE_OTHER = 0;
public ImAdapter(List<ChatMsg> chatMsgList){
this.chatMsgList = chatMsgList;
}
#Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
if (viewType==VIEW_TYPE_USER){
View itemView = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_chat_msg_user,parent,false);
return new ImUserViewHolder(itemView);
}
else {
View itemView = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_chat_msg_other,parent,false);
return new ImOtherViewHolder(itemView);
}
}
#Override
public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
if (holder.getItemViewType()==VIEW_TYPE_USER){
ChatMsg chatMsg = chatMsgList.get(position);
ImUserViewHolder imUserViewHolder = (ImUserViewHolder)holder;
imUserViewHolder.msg.setText(chatMsg.getMsg());
imUserViewHolder.timeStamp.setText(chatMsg.getTime());
}
else {
ChatMsg chatMsg = chatMsgList.get(position);
ImOtherViewHolder imOtherViewHolder = (ImOtherViewHolder) holder;
imOtherViewHolder.msg.setText(chatMsg.getMsg());
imOtherViewHolder.timeStamp.setText(chatMsg.getTime());
}
}
#Override
public int getItemViewType(int position) {
ChatMsg chatMsg = chatMsgList.get(position);
if (chatMsg.getOther().equals("true")){
return VIEW_TYPE_OTHER;
}
else {
return VIEW_TYPE_USER;
}
}
#Override
public int getItemCount() {
return chatMsgList.size();
}
public class ImOtherViewHolder extends RecyclerView.ViewHolder{
public TextView msg;
public TextView timeStamp;
public ImOtherViewHolder(View itemView) {
super(itemView);
msg = (TextView)itemView.findViewById(R.id.tv_chat_msg_other);
timeStamp = (TextView)itemView.findViewById(R.id.tv_time_chat_msg_other);
}
}
public class ImUserViewHolder extends RecyclerView.ViewHolder{
public TextView msg;
public TextView timeStamp;
public ImUserViewHolder(View itemView) {
super(itemView);
msg = (TextView)itemView.findViewById(R.id.tv_chat_msg_user);
timeStamp = (TextView)itemView.findViewById(R.id.tv_time_chat_msg_user);
}
}
}
To you IMAdapter add method
public void setChatMsgList(List<ChatMsg> chatMsgList ) {
this.chatMsgList = chatMsgList;
}
and in your IMActivity in method prepareChatData call this new setChatMsgList method
{
...
chatMsgList.add(chatMsg);
}
imAdapter.setChatMsgList(chatMsgList);
imAdapter.notifyDataSetChanged();

Issue with new POJO Object

I just made my first POJO Class, which takes two Strings and one String array and combines them into one (for lack of a better term) package. Everything seemed to be working well until the very last part. Here is my code:
class dataPOJO extends Phone_Save {
String fName;
String cName;
String[] cText;
public dataPOJO() {
fName = file_name;
cName = cname;
cText = ctext;
}
public String getName() {
return cName;
}
public void setName(String cName) {
this.cName = cName;
}
public String getFileName() {
return fName;
}
public void setFileName(String fName) {
this.fName = fName;
}
public String[] getRemainder() {
return cText;
}
public void getRemainder(String[] cText) {
this.cText = cText;
}
public String toString() {
String savePackage = "File Name: " + getFileName() + "\n";
savePackage += "CName: " + getName() + "\n";
savePackage += getRemainder() + "\n";
return savePackage;
}
public static void main(String[] args) {
dataPOJO combine = new dataPOJO();
combine.setName(cName);
combine.setFileName(fName);
combine.setRemainder(cText);
System.out.println(combine);
}
}
Unfortunately, I cannot setName as any of the strings I referenced above. To me, it seems like I should be able to. And I can't put a default name in there like:
combine.setName("default name");
because the name comes from user input and is different every time. My question is how can I set the value of the String array below to the strings like cName referenced above?
Thanks!
Added code
public class Phone_Save extends ActionBarActivity {
String[] ctext;
public int doc_id = 0;
String cname;
Button fileName;
Button loadText;
String file_name;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_phone_save);
Intent save_intent = getIntent();
Bundle bundle = save_intent.getExtras();
EditText file_name_edit = (EditText) findViewById(R.id.editText);
final TextView loaded_text = (TextView)findViewById(R.id.loaded_text);
file_name = file_name_edit.getText().toString();
fileName = (Button) findViewById(R.id.fName);
loadText = (Button) findViewById(R.id.loadText);
if (bundle != null) {
ctext = bundle.getStringArray("confirmed_text");
cname = bundle.getString("confirmed_name");
}
fileName.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
new dataPOJO();
}
});
}
First, dataPOJO should not be extending Phone_Save. There's nothing dataPOJO needs to do that depends on it being an Activity (at least based on what you've shown us). If you want to have that class to store those information in one place, that's fine; otherwise just store them in Phone_Save itself. Right now you appear to be trying to do both at once, which is confusing.
Second, calling new dataPOJO() in the OnClickListener allocates an object, then discards it since it is not being assigned to anything. It's also a completely different object and has no effect on this one.
Third, there's no use for that main method on Android, it will never be called (unless you call it yourself, which would be pointless anyway).
I would make dataPOJO its own class that doesn't extend anything and get rid of the no-arg constructor (or leave it but remove the code that's in there). In your Phone_Save's onCreate method, you can just make a dataPOJO and hang onto it.
public class DataPojo {
String fName;
String cName;
String[] cText;
public dataPOJO() {}
/* all the other stuff */
}
public class Phone_Save extends ActionBarActivity {
private DataPojo dataPojo;
// other members
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
dataPojo = new DataPojo();
Intent intent = getIntent();
dataPojo.setName(intent.getStringExtra("confirmed_name"));
dataPojo.setRemainder(intent.getStringExtra("confirmed_text"));
// other stuff...
}
}

Categories