onActivityResult Is not responding when choosing from a list - android

Hi Guys I am new with android programming and Java. I am trying to make a travel app. My issue is that how do I pass data from the selected item from the list to the editText filed. This is out I have done so far.. Pls. be kind I am newbee
The activity class that uses the ListActivity
import android.app.ListActivity;
import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Toast;
public class SelectStationActivity extends ListActivity {
String stations[] = { "Acton Main Line","Ealing","Great Western","Albany Park"};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
ArrayAdapter <String> adapter =new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1, stations);
setListAdapter(adapter);
}
protected void OnListItemClick(ListView l, View v, int position, long id) {
String values = stations[(int) id];
Intent result = new Intent().putExtra("SELECTED_STATION_NAME", values);
setResult(RESULT_OK, result);
finish();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.select_station, menu);
return true;
}
The main class
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.widget.SimpleCursorAdapter.ViewBinder;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
public class TravelActivity extends Activity {
// The request code for the selectChkInBt
protected static final int SelectChkin_REQUEST_CODE = 1;
// The request code for the selectChkOutBt
protected static final int SelectChkout_REQUEST_CODE = 2;
private String checkinStation;
private String checkoutStation;
private Button checkinButton, checkoutButton, selectChkInButton, selectChkOutButton;
private EditText checkinEditText, checkoutEditText;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_travel);
checkinButton = (Button) findViewById(R.id.btCkIn);
checkoutButton = (Button) findViewById(R.id.BtChkOut);
selectChkInButton = (Button) findViewById(R.id.btselectChkIn);
selectChkOutButton = (Button) findViewById(R.id.btselectChkOut);
checkinEditText = (EditText) findViewById(R.id.EditTxtChkIn);
checkoutEditText = (EditText) findViewById(R.id.EditTxtChkOut);
checkinButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (checkinEditText.getText().toString().equals("")) {
Toast.makeText(TravelActivity.this,
"Enter Check-in Station", Toast.LENGTH_LONG).show();
} else {
checkinStation = checkinEditText.getText().toString();
// Enable the check-out EditText and Button
checkinEditText.setEnabled(false);
checkinEditText.setTextColor(Color.CYAN);
checkinButton.setEnabled(false);
// Disable the check-in- EdiText AND Button
checkoutEditText.setEnabled(true);
checkoutButton.setEnabled(true);
checkoutEditText.requestFocus();
}
}
});
checkoutButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (checkoutEditText.getText().toString().equals("")) {
Toast.makeText(TravelActivity.this,
"Enter Check-Out station", Toast.LENGTH_LONG)
.show();
} else {
checkoutStation = checkoutEditText.getText().toString();
// Clear edit Text
checkoutEditText.setText("");
// Enable the check-in EditText and Button
checkoutEditText.setEnabled(false);
checkoutButton.setEnabled(false);
/*
* Disable the check-out EditText and Button, to allow the
* eternal cycle of checking in and out to commence once again */
checkinEditText.setText("");
checkinEditText.setEnabled(true);
checkinButton.setEnabled(true);
checkinEditText.requestFocus();
Toast.makeText(getApplicationContext(),
"Travel information added!", Toast.LENGTH_SHORT)
.show();
}
}
});
I could implement a inner class for the two select buttons but i have diffculties to do it.Pls. provide some help how I could implement it thanks.
selectChkInButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(TravelActivity.this,
SelectStationActivity.class);
startActivityForResult(intent, SelectChkin_REQUEST_CODE);
}
});
selectChkOutButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(TravelActivity.this,SelectStationActivity.class);
startActivityForResult(intent, SelectChkout_REQUEST_CODE);
}
});
}
The onActivityResult is not responding here
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode== RESULT_OK){
if (requestCode == 1) {
checkinEditText.setText(data.getStringExtra("SELECTED_STATION_NAME"));
}
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuItem item = menu.add(Menu.NONE, Menu.FIRST, Menu.NONE, "Recipt");
item.setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM);
return true;
}
public boolean OnMenuItemSelected(int featureId, MenuItem item) {
String Recipt = "Recipt" + item.getItemId() + "\nCheck-in: "
+ checkinStation + "\nCheck-Out: " + checkoutStation;
Toast.makeText(getApplicationContext(), Recipt, Toast.LENGTH_LONG)
.show();
return true;
}
protected void OnSaveInstanceState(Bundle outState) {
outState.putString("lAST_CHECKIN", checkinStation);
outState.putString("lAST_CHECKOUT", checkoutStation);
}
protected void onRestoreInstance(Bundle savedInstanceState) {
checkinStation = savedInstanceState.getString(checkinStation);
checkoutStation = savedInstanceState.getString(checkoutStation);
}
}

You Should use this
checkinEditText.setText(data.getStringExtra("SELECTED_STATION_NAME"));
as
checkinEditText.setText(data.getStringExtra("SELECTED_STATION_NAME").toString());

Related

Accessing another activity's method

I have a medicine_activity class
package com.example.shubhmgajra.medikit;
import android.content.Intent;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.Toast;
public class Medicine_Activity extends AppCompatActivity implements View.OnClickListener {
private static final String TAG = "Medicine_Activity";
private Button btnAdd;
private ListView listMeds;
private AppDatabase db;
private ArrayAdapter<MedicineRecord> arrayAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_medicine);
btnAdd = findViewById(R.id.btnAdd);
btnAdd.setOnClickListener(this);
listMeds = findViewById(R.id.listMeds);
listMeds.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
MedicineRecord medicineRecord = db.medicineRecordDao().findMedicineById(id + 1);
Intent intent = new Intent(getApplicationContext(), MedicineInputActivity.class);
startActivity(intent);
MedicineInputActivity.getInstance().update(medicineRecord, true);
}
});
db = AppDatabase.getInstance(getApplicationContext());
FeedAdapter feedAdapter = new FeedAdapter(Medicine_Activity.this, R.layout.list_record, db.medicineRecordDao().loadAllRecords());
listMeds.setAdapter(feedAdapter);
}
#Override
protected void onResume() {
super.onResume();
}
#Override
public void onClick(View v) {
Intent intent = new Intent(this, MedicineInputActivity.class);
startActivity(intent);
}
}
In this i am trying to call update() method of another activity namely MedicineInputActivity
package com.example.shubhmgajra.medikit;
import android.content.Intent;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TimePicker;
import android.widget.Toast;
public class MedicineInputActivity extends AppCompatActivity implements View.OnClickListener {
private static final String TAG = "MedicineInputActivity";
static EditText dosage;
static EditText medName;
static TimePicker timePicker;
static Button btnSave;
Button btnInc;
Button btnDec;
private AppDatabase db;
private static MedicineInputActivity instance;
boolean isEdit;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_medicine_input);
isEdit = false;
instance = this;
dosage = findViewById(R.id.dosage);
dosage.setShowSoftInputOnFocus(false);
dosage.setCursorVisible(false);
medName = findViewById(R.id.medName);
timePicker = findViewById(R.id.simpleTimePicker);
btnInc = findViewById(R.id.btnInc);
btnDec = findViewById(R.id.btnDec);
btnInc.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String val = dosage.getText().toString();
int tempVal = Integer.parseInt(val);
tempVal++;
dosage.setText("" + tempVal);
}
});
btnDec.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String val = dosage.getText().toString();
int tempVal = Integer.parseInt(val);
if (tempVal > 0) {
tempVal--;
}
dosage.setText("" + tempVal);
}
});
btnSave = findViewById(R.id.btnSave);
btnSave.setOnClickListener(this);
db = AppDatabase.getInstance(getApplicationContext());
}
#Override
public void onClick(View v) {
String name = medName.getText().toString();
int min = timePicker.getMinute();
int hour = timePicker.getHour();
String val = dosage.getText().toString();
int dose = Integer.parseInt(val);
MedicineRecord medicineRecord = new MedicineRecord(name, dose, min, hour);
if (validate(name)) {
if (isEdit) {
db.medicineRecordDao().updateRecord(medicineRecord);
} else {
db.medicineRecordDao().insertRecord(medicineRecord);
}
Intent intent = new Intent(this, Medicine_Activity.class);
startActivity(intent);
} else {
Toast toast = Toast.makeText(getApplicationContext(), "Medicine name cannot be empty", Toast.LENGTH_SHORT);
toast.show();
}
}
private boolean validate(String name) {
if (name.length() == 0) {
return false;
} else {
return true;
}
}
public static MedicineInputActivity getInstance() {
return instance;
}
public void update(MedicineRecord medicineRecord, boolean isEdit) {
this.isEdit = isEdit;
dosage.setText(medicineRecord.getDosage());
medName.setText(medicineRecord.getMedName());
timePicker.setHour(medicineRecord.getHour());
timePicker.setMinute(medicineRecord.getMinute());
}
}
What i am trying to achieve is when the user taps the list item, the input activity is loaded and the user can update the record. I wasnt able to find an elegant solution other than making an update method in MedicineInputActivity and then getting an instance of MedicineInputActivity in Medicine_Activity and calling update.
I am getting errors like "Attempt to invoke virtual method 'void com.example.shubhmgajra.medikit.MedicineInputActivity.update() on a null object reference".
You can return data from second activity to the first activity when user is done updating the record. You should start second activity by calling startActivityForResult() instead of startActivity() in the first activity. You should also override onActivityResult() in the first activity. You can read more here.
UPDATE:
I think you want to send selected medicine details from Medicine_Activity to MedicineInputActivity. In that case, you can send selected medicine object by binding it to the intent as follows:
public class Medicine_Activity ... {
#Override
protected void onCreate(Bundle savedInstanceState) {
...
listMeds.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
MedicineRecord medicineRecord = db.medicineRecordDao().findMedicineById(id + 1);
Intent intent = new Intent(getApplicationContext(), MedicineInputActivity.class);
intent.putExtra("selectedMedicine", medicineRecord);
startActivity(intent);
MedicineInputActivity.getInstance().update(medicineRecord, true);
}
});
...
}
}
Then on MedicineInputActivity, you should be doing this:
public class MedicineInputActivity ... {
MedicineRecord selectedMedicineRecord;
#Override
protected void onCreate(Bundle savedInstanceState) {
...
selectedMedicineRecord = (MedicineRecord) getIntent().getParcelableExtra("selectedMedicine");
...
}
}
To be able to do this, your MedicineRecord class should implement Parcelable interface.

My extra data doesn't appear immediately

In my file Reservation.java I have a function that loads LieuActivity.
So this is the function
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
public class Reservation extends AppCompatActivity implements View.OnClickListener {
private Button end,deb,lieu,type,cherch;
private TextView type_v ;
private ImageView car;
private View division;
private ListView list;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_reservation);
end = (Button)findViewById( R.id.btn_fin );
end.setOnClickListener( this);
deb= (Button)findViewById( R.id.deb_btn);
deb.setOnClickListener( this );
lieu = (Button)findViewById( R.id.btn_local);
lieu.setOnClickListener( this );
type = (Button)findViewById( R.id.btn_type);
type.setOnClickListener( this );
cherch= (Button)findViewById( R.id.btn_cherch);
cherch.setOnClickListener( this );
division= (View)findViewById( R.id.div3);
type_v= (TextView)findViewById( R.id.type);
car= (ImageView) findViewById( R.id.pic_car);
list=(ListView)findViewById(R.id.fin_list);
ArrayAdapter<String> mAdapter= new ArrayAdapter<String>(Reservation.this, android.R.layout.simple_list_item_1, getResources().getStringArray(R.array.values));
list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
if (position == 3 )
{
Intent i = new Intent(view.getContext(),Deb_FinActivity.class);
startActivityForResult(i,3);
}
}
});
list.setAdapter(mAdapter);
}
#Override
public void onClick(View view) {
switch(view.getId())
{
case R.id.deb_btn:
loadDebActivity();
break;
case R.id.btn_fin:
loadFin();
break;
case R.id.btn_local:
loadLieuActivity();
break;
case R.id.btn_type:
loadTypeActivity();
break;
case R.id.btn_cherch:
loadSearch();
break;
}
}
private void loadDebActivity()
{
startActivity(new Intent( this,Deb_FinActivity.class ) );
finish();
}
private void loadFin()
{
lieu.setVisibility( View.INVISIBLE );
type.setVisibility(View.INVISIBLE);
cherch.setVisibility(View.INVISIBLE);
car.setVisibility(View.INVISIBLE);
division.setVisibility(View.INVISIBLE);
type_v.setVisibility(View.INVISIBLE);
list.setVisibility(View.VISIBLE);
}
private void loadLieuActivity()
{
startActivity(new Intent( this,LieuActivity.class ) );
lieu.setText(getIntent().getStringExtra("mytext"));
}
private void loadTypeActivity()
{
startActivity(new Intent( this,TypeActivity.class ) );
finish();
}
private void loadSearch()
{
}
}
In my LieuActivity.java I have this code
public class LieuActivity extends AppCompatActivity {
private EditText lieuu;
private TextView local;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_lieu);
addListenerOnButton();
}
public void addListenerOnButton() {
local = (TextView) findViewById(R.id.position);
local.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
EditText lieuu = (EditText)findViewById(R.id.local);
String text =lieuu.getText().toString();
Intent myIntent = new Intent(view.getContext(),Reservation.class);
myIntent.putExtra("mytext",text);
startActivity(myIntent);
}
});
}
}
The problem is when I edit in my LieuActivity and go back to reservation it does not return the extra value until I click another time on the editText so I see the updated data for a second before re-going to LieuActivity and modify it another time .
Put these lines in onCreate() of Reservation activity
String text = getIntent().getStringExtra("mytext");
if (text != null) {
lieu.setText(text);
}
and make this change:
private void loadLieuActivity()
{
startActivity(new Intent( this,LieuActivity.class ) );
finish();
}
Do this in oncreate of Reservation
Bundle extras = getIntent().getExtras();
String string;
if (extras != null) {
string = extras.getString("mytext");
lieu.setText(string);
}
Make changes like this in LieuActivity :-
public class LieuActivity extends AppCompatActivity {
private EditText lieuu;
private TextView local;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_lieu);
addListenerOnButton();
}
public void addListenerOnButton() {
local = (TextView) findViewById(R.id.position);
local.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
EditText lieuu = (EditText)findViewById(R.id.local);
String text =lieuu.getText().toString();
Intent myIntent = new Intent(view.getContext(),Reservation.class);
myIntent.putExtra("mytext",text);
setResult(RESULT_OK, myIntent );
});
}
}
In Reservation put onActivityResult()
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
public class Reservation extends AppCompatActivity implements View.OnClickListener {
private Button end,deb,lieu,type,cherch;
private TextView type_v ;
private ImageView car;
private View division;
private ListView list;
String mNewText="";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_reservation);
end = (Button)findViewById( R.id.btn_fin );
end.setOnClickListener( this);
deb= (Button)findViewById( R.id.deb_btn);
deb.setOnClickListener( this );
lieu = (Button)findViewById( R.id.btn_local);
lieu.setOnClickListener( this );
type = (Button)findViewById( R.id.btn_type);
type.setOnClickListener( this );
cherch= (Button)findViewById( R.id.btn_cherch);
cherch.setOnClickListener( this );
division= (View)findViewById( R.id.div3);
type_v= (TextView)findViewById( R.id.type);
car= (ImageView) findViewById( R.id.pic_car);
list=(ListView)findViewById(R.id.fin_list);
ArrayAdapter<String> mAdapter= new ArrayAdapter<String>(Reservation.this, android.R.layout.simple_list_item_1, getResources().getStringArray(R.array.values));
list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
if (position == 3 )
{
Intent i = new Intent(view.getContext(),Deb_FinActivity.class);
startActivityForResult(i,3);
}
}
});
list.setAdapter(mAdapter);
}
#Override
public void onClick(View view) {
switch(view.getId())
{
case R.id.deb_btn:
loadDebActivity();
break;
case R.id.btn_fin:
loadFin();
break;
case R.id.btn_local:
loadLieuActivity();
break;
case R.id.btn_type:
loadTypeActivity();
break;
case R.id.btn_cherch:
loadSearch();
break;
}
}
private void loadDebActivity()
{
startActivity(new Intent( this,Deb_FinActivity.class ) );
finish();
}
private void loadFin()
{
lieu.setVisibility( View.INVISIBLE );
type.setVisibility(View.INVISIBLE);
cherch.setVisibility(View.INVISIBLE);
car.setVisibility(View.INVISIBLE);
division.setVisibility(View.INVISIBLE);
type_v.setVisibility(View.INVISIBLE);
list.setVisibility(View.VISIBLE);
}
private void loadLieuActivity()
{
startActivity(new Intent( this,LieuActivity.class ) );
lieu.setText(mNewText);
}
private void loadTypeActivity()
{
startActivity(new Intent( this,TypeActivity.class ) );
finish();
}
private void loadSearch()
{
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == QUEUE_MSG) {
if (resultCode == RESULT_OK) {
Serializable myText= data.getSerializableExtra("mytext");
if (myText!= null)
mNewText= myText;
}
}
}
}
Hope this may help you

Chat messages are not showed when exit and reopen app

I have made a chat app using this lesson. I have tested it:
Then I closed the app, and opened it some time later. And surprisingly all messages had disappeared:
They appeared back only when I logged out and logged in again.
How to solve that bug?
My code:
MainActivity.java:
import android.content.Intent;
import android.support.annotation.NonNull;
import android.support.design.widget.FloatingActionButton;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.Toast;
import com.firebase.ui.auth.AuthUI;
import com.firebase.ui.database.FirebaseListAdapter;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.database.FirebaseDatabase;
public class MainActivity extends AppCompatActivity {
private static final int SIGN_IN_REQUEST_CODE = 111;
private FirebaseListAdapter<ChatMessage> adapter;
private ListView listView;
private String loggedInUserName = "";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//find views by Ids
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
final EditText input = (EditText) findViewById(R.id.input);
listView = (ListView) findViewById(R.id.list);
if (FirebaseAuth.getInstance().getCurrentUser() == null) {
// Start sign in/sign up activity
startActivityForResult(AuthUI.getInstance()
.createSignInIntentBuilder()
.build(), SIGN_IN_REQUEST_CODE);
} else {
// User is already signed in, show list of messages
showAllOldMessages();
}
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (input.getText().toString().trim().equals("")) {
Toast.makeText(MainActivity.this, "Please enter some texts!", Toast.LENGTH_SHORT).show();
} else {
FirebaseDatabase.getInstance()
.getReference()
.push()
.setValue(new ChatMessage(input.getText().toString(),
FirebaseAuth.getInstance().getCurrentUser().getDisplayName(),
FirebaseAuth.getInstance().getCurrentUser().getUid())
);
input.setText("");
}
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if (item.getItemId() == R.id.menu_sign_out) {
AuthUI.getInstance().signOut(this)
.addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
Toast.makeText(MainActivity.this, "You have logged out!", Toast.LENGTH_SHORT).show();
finish();
}
});
}
return true;
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == SIGN_IN_REQUEST_CODE) {
if (resultCode == RESULT_OK) {
Toast.makeText(this, "Signed in successful!", Toast.LENGTH_LONG).show();
showAllOldMessages();
} else {
Toast.makeText(this, "Sign in failed, please try again later", Toast.LENGTH_LONG).show();
// Close the app
finish();
}
}
}
private void showAllOldMessages() {
loggedInUserName = FirebaseAuth.getInstance().getCurrentUser().getUid();
Log.d("Main", "user id: " + loggedInUserName);
adapter = new MessageAdapter(this, ChatMessage.class, R.layout.item_in_message,
FirebaseDatabase.getInstance().getReference());
listView.setAdapter(adapter);
}
public String getLoggedInUserName() {
return loggedInUserName;
}
}
ChatMessage.java:
public class ChatMessage {
private String messageText;
private String messageUser;
private String messageUserId;
public ChatMessage(String messageText, String messageUser, String messageUserId) {
this.messageText = messageText;
this.messageUser = messageUser;
this.messageUserId = messageUserId;
}
public ChatMessage(){
}
public String getMessageUserId() {
return messageUserId;
}
public void setMessageUserId(String messageUserId) {
this.messageUserId = messageUserId;
}
public String getMessageText() {
return messageText;
}
public void setMessageText(String messageText) {
this.messageText = messageText;
}
public String getMessageUser() {
return messageUser;
}
public void setMessageUser(String messageUser) {
this.messageUser = messageUser;
}
}
ChatAdapter.java:
import android.text.format.DateFormat;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import com.firebase.ui.database.FirebaseListAdapter;
import com.google.firebase.database.DatabaseReference;
public class MessageAdapter extends FirebaseListAdapter<ChatMessage> {
private MainActivity activity;
public MessageAdapter(MainActivity activity, Class<ChatMessage> modelClass, int modelLayout, DatabaseReference ref) {
super(activity, modelClass, modelLayout, ref);
this.activity = activity;
}
#Override
protected void populateView(View v, ChatMessage model, int position) {
TextView messageText = (TextView) v.findViewById(R.id.message_text);
TextView messageUser = (TextView) v.findViewById(R.id.message_user);
messageText.setText(model.getMessageText());
messageUser.setText(model.getMessageUser());
}
#Override
public View getView(int position, View view, ViewGroup viewGroup) {
ChatMessage chatMessage = getItem(position);
if (chatMessage.getMessageUserId().equals(activity.getLoggedInUserName()))
view = activity.getLayoutInflater().inflate(R.layout.item_out_message, viewGroup, false);
else
view = activity.getLayoutInflater().inflate(R.layout.item_in_message, viewGroup, false);
//generating view
populateView(view, chatMessage, position);
return view;
}
#Override
public int getViewTypeCount() {
// return the total number of view types. this value should never change
// at runtime
return 2;
}
#Override
public int getItemViewType(int position) {
// return a value between 0 and (getViewTypeCount - 1)
return position % 2;
}
}
P.S I have tried to paste code below into onResume method of MainActivity but nothing good is happening.
if (FirebaseAuth.getInstance().getCurrentUser() == null) {
// Start sign in/sign up activity
startActivityForResult(AuthUI.getInstance()
.createSignInIntentBuilder()
.build(), SIGN_IN_REQUEST_CODE);
} else {
// User is already signed in, show list of messages
showAllOldMessages();
}
P.P.S When I try to send new messages in chat, when there is a bug, I see them. But when I log out and login again, these messages are absent.
Check the logs when you close and re-open the app or if you want a tutorial here's one that uses firebase to create a chat application.
Part-1 https://www.youtube.com/watch?v=wVCz1a3ogqk
Part-2 https://www.youtube.com/watch?v=uX6_w6yhj4E

how to restore RecyclerView?

I have the following situation:
I have two activities (Main Activity and ProductCard Activity)
Main Activity has a RecyclerView with items in it.
( User can add items manually. For example he add 3 items)
User click on some item and go to the ProductCard Activity
In the ProductCard Activity user click on the button (moneyOk_readylist) and go to the Main Activity
But when User do last step, RecyclerView become blank (empty).
I know that it is connected with states, but doesn't understand how.
Can anyone help me?
MainActivity
import android.content.Intent;
import android.os.Bundle;
import android.os.PersistableBundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.CardView;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.View;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.Toast;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
public class MainActivity extends AppCompatActivity {
private List<Person> persons;
private RecyclerView rv;
final String LOG_TAG = "myLogs";
RVAdapter adapter;
Person person;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
rv = (RecyclerView)findViewById(R.id.rv);
rv.setHasFixedSize(true);
LinearLayoutManager llm = new LinearLayoutManager(this);
rv.setLayoutManager(llm);
persons = new ArrayList<>();
adapter = new RVAdapter(persons);
rv.setAdapter(adapter);
if ((savedInstanceState != null) && (savedInstanceState.getSerializable("card") != null)) {
persons.clear();
persons.addAll((List<Person>) savedInstanceState.getSerializable("card"));
adapter.notifyDataSetChanged();
Log.d(LOG_TAG, "restore card with persons" + persons);
}
adapter.setOnItemClickListener(new RVAdapter.MyClickListener() {
#Override
public void onItemClick(int position, View v) {
Toast.makeText(MainActivity.this, "push on item" + position, Toast.LENGTH_SHORT).show();
Intent intent = new Intent(MainActivity.this, ProductCard.class);
startActivity(intent);
Log.d(LOG_TAG, "go to ProductCard class" + persons);
}
});
adapter.setOnItemLongClickListener(new RVAdapter.MyLongClickListener() {
#Override
public void onItemLongClick(int position, View v) {
Toast.makeText(MainActivity.this, "push on item long" + position, Toast.LENGTH_SHORT).show();
Log.d(LOG_TAG, "Removed " + position);
persons.remove(position);
adapter.notifyDataSetChanged();
}
});
setSupportActionBar(toolbar);
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
person= new Person("Emma Wilson", "23 years old", R.drawable.im_beach);
persons.add(person);
Log.d(LOG_TAG, "push add" + persons);
adapter.notifyDataSetChanged();
}
});
}
#Override
protected void onResume() {
super.onResume();
adapter = new RVAdapter(persons);
rv.setAdapter(adapter);
Log.d(LOG_TAG, "onresume" + persons);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putSerializable("card", (Serializable) persons);
Log.d(LOG_TAG, "save cards" + persons);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
ProductCard Activity
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.Toast;
/**
* Created by Dmitry on 01.11.2015.
*/
public class ProductCard extends AppCompatActivity implements AdapterView.OnItemClickListener {
final String LOG_TAG = "myLogs";
Button moneyOk_readylist;
ImageButton addPhoto;
ImageView imageView;
private static int LOAD_IMAGE_RESULTS = 1;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.product_card);
moneyOk_readylist=(Button)findViewById(R.id.moneyOk_readylist);
addPhoto=(ImageButton)findViewById(R.id.add_photo);
imageView=(ImageView)findViewById(R.id.imageView);
addPhoto.setOnLongClickListener(new View.OnLongClickListener() {
#Override
public boolean onLongClick(View v) {
return false;
}
});
addPhoto.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent i = new Intent(Intent.ACTION_PICK,
android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
i.setType("image/*");
//i.setAction(Intent.ACTION_PICK);
startActivityForResult(Intent.createChooser(i,"Select picture"),1);
}
});
moneyOk_readylist.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent=new Intent(ProductCard.this,MainActivity.class);
startActivity(intent);
}
});
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
// Here we need to check if the activity that was triggers was the Image Gallery.
// If it is the requestCode will match the LOAD_IMAGE_RESULTS value.
// If the resultCode is RESULT_OK and there is some data we know that an image was picked.
if (requestCode == 1 && resultCode == RESULT_OK && data != null) {
// Let's read picked image data - its URI
imageView.setImageURI(data.getData());
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
switch (id) {
case R.id.action_save_card:
Toast.makeText(ProductCard.this, "Карточка сохранена", Toast.LENGTH_SHORT).show();
Intent intent=new Intent(ProductCard.this,MainActivity.class);
startActivity(intent);
Log.d(LOG_TAG, "go to Main class" );
break;
case R.id.action_delete_card:
Toast.makeText(ProductCard.this, "Карточка удалена", Toast.LENGTH_SHORT).show();
break;
}
return true;
}
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
}
}

Text To Speech error

Can any let me know what I am doing wrong. Trying to get Text To Speech to work onClick for a Text View.
import android.app.Activity;
import android.os.Bundle;
import android.widget.Button;
import android.widget.TextView;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.content.Intent;
import android.speech.tts.TextToSpeech;
public class MainActivity extends Activity implements TextToSpeech.OnInitListener
{
private TextToSpeech tts;
private static final int MY_DATA_CHECK_CODE = 1234;
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.layout_24);
Intent checkIntent = new Intent();
checkIntent.setAction(TextToSpeech.Engine.ACTION_CHECK_TTS_DATA);
startActivityForResult(checkIntent, MY_DATA_CHECK_CODE);
((Button)findViewById(R.id.btnClear)) .setOnClickListener(clearbutton);
}
public void onClick(View v)
{
TextView textSpeak = (TextView) findViewById(R.id.mainText);
tts.speak(textSpeak.getText(), TextToSpeech.QUEUE_FLUSH, null);
}
public void onInit( int i)
{
}
public void onActivityResult(int requestCode, int resultCode, Intent data)
{
if (requestCode == MY_DATA_CHECK_CODE)
{
if (resultCode == TextToSpeech.Engine.CHECK_VOICE_DATA_PASS)
{
tts = new TextToSpeech(this, this);
}
else
{
Intent installIntent = new Intent();
installIntent.setAction(TextToSpeech.Engine.ACTION_CHECK_TTS_DATA);
startActivity(installIntent);
}
}
}
public void onDestory()
{
if (tts != null)
{
tts.stop();
tts.shutdown();
}
super.onDestroy();
}
OnClickListener clearbutton = new OnClickListener()
{
public void onClick(View v)
{
TextView mainText = (TextView)findViewById(R.id.mainText);
mainText.setText("");
}
};
#Override
public boolean onCreateOptionsMenu(Menu menu)
{
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.menu, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item)
{
switch (item.getItemId())
{
case R.id.select8icons: setContentView(R.layout.layout_8);
break;
case R.id.select24icons: setContentView(R.layout.layout_24);
break;
case R.id.select63icons: setContentView(R.layout.layout_63);
break;
}
return true;
}
}
If anyone can help or has a better way to run the code, I love to hear your ideals. I try to research but every way I try gave me a error or something. Thanks in advance.
Your button will not work until TextToSpeech calls onInit. So you should disable btnSpeak until then.
Your TTS stuff looks fine. However, I dont see where you are binding any button to your onClick method and neither does your Activity seem to implement the onClickListener interface. You would need to do one or the other to get that onClick method to run.
So basically, I dont see any way your onClick method will ever get called.
Assuming you have some view/button in your layout the user is supposed to click to hear the tts, I think you want something like:
Button btnSpeak = (Button)findViewById(R.id.btnSpeak);
btnSpeak.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
TextView textSpeak = (TextView) findViewById(R.id.mainText);
tts.speak(textSpeak.getText(), TextToSpeech.QUEUE_FLUSH, null);
}
});

Categories

Resources