Unable to run multiple bluetooth connection - android

this the main activity java file of my code
package com.ramimartin.sample.multibluetooth;
import android.bluetooth.BluetoothDevice;
import android.os.Bundle;
import android.support.v4.app.DialogFragment;
import android.support.v4.app.FragmentTransaction;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ListView;
import android.widget.ToggleButton;
import com.ramimartin.multibluetooth.activity.BluetoothFragmentActivity;
import com.ramimartin.multibluetooth.bluetooth.mananger.BluetoothManager;
import java.util.ArrayList;
import java.util.List;
import butterknife.ButterKnife;
import butterknife.InjectView;
import butterknife.OnClick;
public class MainActivity extends BluetoothFragmentActivity implements DiscoveredDialogFragment.DiscoveredDialogListener {
#InjectView(R.id.listview)
ListView mListView;
ArrayAdapter<String> mAdapter;
List<String> mListLog;
#InjectView(R.id.communication)
EditText mEditText;
#InjectView(R.id.send)
ImageButton mSendBtn;
#InjectView(R.id.client)
ToggleButton mClientToggleBtn;
#InjectView(R.id.serveur)
ToggleButton mServerToggleBtn;
#InjectView(R.id.connect)
Button mConnectBtn;
#InjectView(R.id.disconnect)
Button mDisconnect;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ButterKnife.bind(this);
mListLog = new ArrayList<String>();
mAdapter = new ArrayAdapter<String>(this, R.layout.item_console, mListLog);
mListView.setAdapter(mAdapter);
}
#Override
public int myNbrClientMax() {
return 7;
}
#OnClick(R.id.serveur)
public void serverType() {
setLogText("===> Start Server ! Your mac address : " + mBluetoothManager.getYourBtMacAddress());
setTimeDiscoverable(BluetoothManager.BLUETOOTH_TIME_DICOVERY_3600_SEC);
selectServerMode();
mServerToggleBtn.setChecked(true);
mClientToggleBtn.setChecked(false);
mConnectBtn.setEnabled(true);
mConnectBtn.setText("Scan Devices");
}
#OnClick(R.id.client)
public void clientType() {
setLogText("===> Start Client ! Your mac address : " + mBluetoothManager.getYourBtMacAddress());
setTimeDiscoverable(BluetoothManager.BLUETOOTH_TIME_DICOVERY_120_SEC);
selectClientMode();
mServerToggleBtn.setChecked(false);
mClientToggleBtn.setChecked(true);
mConnectBtn.setEnabled(true);
}
#OnClick(R.id.connect)
public void connect() {
setLogText("===> Start Scanning devices ...");
if (getTypeBluetooth() == BluetoothManager.TypeBluetooth.Client) {
showDiscoveredDevicesDialog();
}
scanAllBluetoothDevice();
}
#OnClick(R.id.disconnect)
public void disconnect() {
setLogText("===> Disconnect");
disconnectClient();
disconnectServer();
}
#OnClick(R.id.send)
public void send() {
if (isConnected()) {
sendMessage(mEditText.getText().toString());
setLogText("===> Send : " + mEditText.getText().toString());
}
}
#Override
public void onBluetoothStartDiscovery() {
setLogText("===> Start discovering ! Your mac address : " + mBluetoothManager.getYourBtMacAddress());
}
#Override
public void onBluetoothDeviceFound(BluetoothDevice device) {
if(getTypeBluetooth() == BluetoothManager.TypeBluetooth.Server) {
setLogText("===> Device detected and Thread Server created for this address : " + device.getAddress());
}else{
setLogText("===> Device detected : "+ device.getAddress());
}
}
#Override
public void onClientConnectionSuccess() {
setLogText("===> Client Connexion success !");
mEditText.setText("Client");
mSendBtn.setEnabled(true);
mConnectBtn.setEnabled(false);
mDisconnect.setEnabled(true);
}
#Override
public void onClientConnectionFail() {
setLogText("===> Client Connexion fail !");
mServerToggleBtn.setChecked(false);
mClientToggleBtn.setChecked(false);
mDisconnect.setEnabled(false);
mConnectBtn.setEnabled(false);
mConnectBtn.setText("Connect");
mEditText.setText("");
}
#Override
public void onServeurConnectionSuccess() {
setLogText("===> Serveur Connexion success !");
mEditText.setText("Server");
mDisconnect.setEnabled(true);
}
#Override
public void onServeurConnectionFail() {
setLogText("===> Serveur Connexion fail !");
}
#Override
public void onBluetoothCommunicator(String messageReceive) {
setLogText("===> receive msg : " + messageReceive);
}
#Override
public void onBluetoothNotAviable() {
setLogText("===> Bluetooth not aviable on this device");
mSendBtn.setEnabled(false);
mClientToggleBtn.setEnabled(false);
mServerToggleBtn.setEnabled(false);
mConnectBtn.setEnabled(false);
mDisconnect.setEnabled(false);
}
public void setLogText(String text) {
mListLog.add(text);
mAdapter.notifyDataSetChanged();
mListView.setSelection(mListView.getCount() - 1);
}
private void showDiscoveredDevicesDialog() {
String tag = DiscoveredDialogFragment.class.getSimpleName();
DiscoveredDialogFragment fragment = DiscoveredDialogFragment.newInstance();
fragment.setListener(this);
showDialogFragment(fragment, tag);
}
private void showDialogFragment(DialogFragment dialogFragment, String tag) {
FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
ft.add(dialogFragment, tag);
ft.commitAllowingStateLoss();
}
#Override
public void onDeviceSelectedForConnection(String addressMac) {
setLogText("===> Connect to " + addressMac);
createClient(addressMac);
}
#Override
public void onScanClicked() {
scanAllBluetoothDevice();
}
}
****************************************************************************************************************************************************
here is layout of the application
stackoverflow does not allow me to ask question , i am beginner , very tough to ask question plz try to find out error
ur response will be appreciated
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#android:color/black">
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="#drawable/rami_logo"
android:layout_centerHorizontal="true"/>
<ListView
android:id="#+id/listview"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_above="#+id/communication"
android:divider="#android:color/transparent"
android:layout_alignParentTop="true">
</ListView>
<EditText
android:id="#+id/communication"
android:layout_above="#+id/connexion"
android:singleLine="true"
android:layout_toLeftOf="#+id/send"
android:layout_marginBottom="2dp"
android:textColor="#android:color/white"
android:dividerHeight="0dip"
android:layout_marginTop="2dp"
android:layout_width="match_parent"
android:layout_height="wrap_content"/>
<ImageButton
android:id="#+id/send"
android:layout_above="#+id/connexion"
android:layout_alignTop="#+id/communication"
android:layout_alignParentRight="true"
android:layout_width="60dp"
android:layout_height="wrap_content"
android:src="#drawable/send"/>
<LinearLayout
android:id="#+id/connexion"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_above="#+id/connect"
android:padding="2dp">
<ToggleButton
android:id="#+id/client"
android:layout_weight="1"
android:enabled="true"
android:textColor="#android:color/white"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textOff="Client"
android:textOn="Client"/>
<ToggleButton
android:id="#+id/serveur"
android:layout_weight="1"
android:enabled="true"
android:textColor="#android:color/white"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textOff="Serveur"
android:textOn="Serveur"/>
</LinearLayout>
<Button
android:id="#+id/connect"
android:layout_weight="1"
android:layout_margin="2dp"
android:enabled="false"
android:textColor="#android:color/white"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_above="#+id/disconnect"
android:text="Connect"/>
<Button
android:id="#+id/disconnect"
android:layout_margin="2dp"
android:enabled="false"
android:textColor="#android:color/white"
android:layout_alignParentBottom="true"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Disconnect"/>
</RelativeLayout>
log errorerror log

Related

Data doesn't show in recyclerView, need to go back to show it

I want to create an activity to search for users by full name. I created everything I needed and it worked properly, except for one thing. When I press search button the result are not show in recyclerview. I need to go back and the the results are shown. I need to do these 2 steps to see the results.
Yes the search bar and view holder are overlap, I will try to fixed later. Do you know how to make it so that once searched the results are displayed immediately without having to go back
This is my layout for view holder
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="75dp"
android:layout_marginLeft="5dp"
android:layout_marginRight="5dp"
android:layout_marginTop="5dp"
android:id="#+id/parent_layout"
android:background="#drawable/recycler_view_border">
<com.mikhaellopez.circularimageview.CircularImageView
android:id="#+id/imageProfile"
android:layout_width="60dp"
android:layout_height="60dp"
android:tint="#808080"
android:layout_marginStart="10dp"
android:layout_marginTop="7dp"
app:civ_border_color="#color/dark_blue"
app:civ_border_width="2dp"
app:srcCompat="#drawable/defaultimage"/>
<TextView
android:id="#+id/userFullName"
android:layout_toEndOf="#+id/imageProfile"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="25dp"
android:layout_marginEnd="20dp"
android:layout_marginStart="10dp"
android:gravity="center"
android:text="#string/fullname"
android:textSize="16sp"
android:textColor="#color/black"/>
<com.google.android.material.button.MaterialButton
android:id="#+id/buttonAdd"
android:layout_width="50dp"
android:layout_height="50dp"
android:layout_marginTop="13dp"
android:layout_marginEnd="10dp"
android:layout_marginStart="340dp"
android:background="#drawable/btn_background"
app:cornerRadius="8dp"
android:drawableTop="#drawable/ic_action_add" />
</RelativeLayout>
This is my layout for activity
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".SendFriendRequests">
<LinearLayout
android:id="#+id/linearlayout"
android:layout_width="match_parent"
android:layout_height="100dp"
android:layout_marginLeft="13dp"
android:orientation="vertical"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent">
<EditText
android:id="#+id/searchUsername"
android:layout_width="318dp"
android:layout_height="45dp"
android:layout_marginTop="20dp"
android:background="#drawable/edt_background"
android:hint="#string/searchFriends"
android:imeOptions="actionNext"
android:importantForAutofill="no"
android:inputType="text"
android:paddingStart="16dp"
android:paddingEnd="16dp" />
<com.google.android.material.button.MaterialButton
android:id="#+id/buttonSearch"
android:layout_width="50dp"
android:layout_height="50dp"
android:layout_marginStart="333dp"
android:layout_marginTop="-47dp"
android:layout_marginEnd="10dp"
android:background="#drawable/btn_background"
android:drawableTop="#drawable/ic_action_search"
app:cornerRadius="8dp" />
</LinearLayout>
<androidx.recyclerview.widget.RecyclerView
android:id="#+id/recyclerView"
android:layout_width="match_parent"
android:layout_height="580dp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintTop_toBottomOf="#+id/linearlayout"
app:layout_constraintVertical_bias="0.99"
tools:layout_editor_absoluteX="-16dp" />
</androidx.constraintlayout.widget.ConstraintLayout>
This is my adapter
package com.example.chatappjava;
import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;
import androidx.recyclerview.widget.RecyclerView;
import com.bumptech.glide.Glide;
import com.mikhaellopez.circularimageview.CircularImageView;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.ArrayList;
public class SendFriendRequestAdapter extends RecyclerView.Adapter<SendFriendRequestAdapter.ViewHolder> {
private static final String TAG = "ContactsAdapter";
private ArrayList<UserData> arrayListUserData = new ArrayList<>();
private Context context;
public SendFriendRequestAdapter(ArrayList<UserData> arrayListUserData, Context context) {
this.arrayListUserData = arrayListUserData;
this.context = context;
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.activity_send_friend_request_item, parent, false);
ViewHolder holder = new ViewHolder(view);
return holder;
}
#Override
public void onBindViewHolder(ViewHolder holder, #SuppressLint("RecyclerView") int position) {
Log.d(TAG, "onBindViewHolder: called.");
Glide.with(context)
.asBitmap()
.load(arrayListUserData.get(position).image)
.into(holder.userProfileImage);
holder.userFullName.setText(arrayListUserData.get(position).name);
holder.buttonAdd.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
try {
Connection conn = DatabaseConnection.createDatabaseConnection();
PreparedStatement st1 = conn.prepareStatement(
" insert into FRIEND_REQUESTS values (?,?,?)");
st1.setString(1, arrayListUserData.get(position).friendId);
st1.setString(2, arrayListUserData.get(position).userId);
st1.setInt(3, 0);
st1.execute();
showToast("Friend request is sended");
Intent intent = new Intent(context, MainActivity.class);
intent.putExtra("IdAccount", arrayListUserData.get(position).userId);
context.startActivity(intent);
} catch (SQLException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
});
holder.parentLayout.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(context.getApplicationContext(), specificchat.class);
intent.putExtra("userId", arrayListUserData.get(position).userId);
intent.putExtra("friendId", arrayListUserData.get(position).friendId);
intent.putExtra("friendName", arrayListUserData.get(position).name);
intent.putExtra("friendImage", arrayListUserData.get(position).image);
context.startActivity(intent);
}
});
}
private void showToast(String message) {
Toast.makeText(context.getApplicationContext(), message, Toast.LENGTH_SHORT).show();
}
#Override
public int getItemCount() {
return arrayListUserData.size();
}
public class ViewHolder extends RecyclerView.ViewHolder {
CircularImageView userProfileImage;
TextView userFullName;
RelativeLayout parentLayout;
Button buttonAdd;
public ViewHolder(View itemView) {
super(itemView);
userProfileImage = itemView.findViewById(R.id.imageProfile);
userFullName = itemView.findViewById(R.id.userFullName);
parentLayout = itemView.findViewById(R.id.parent_layout);
buttonAdd = itemView.findViewById(R.id.buttonAdd);
}
}
}
And this is my java class which use the adapter
package com.example.chatappjava;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
public class SendFriendRequests extends AppCompatActivity {
private ArrayList<UserData> arrayListUserData = new ArrayList<>();
private Button searchButton;
private EditText searchUsername;
private String userId;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Intent intent = getIntent();
userId = intent.getStringExtra("IdAccount");
setContentView(R.layout.activity_send_friend_request);
searchButton = findViewById(R.id.buttonSearch);
searchUsername = findViewById(R.id.searchUsername);
searchButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
try {
Connection conn = DatabaseConnection.createDatabaseConnection();
Statement statement = conn.createStatement();
ResultSet resultat = statement.executeQuery("select ID, FULLNAME, IMAGE from USERS where ID not in (select FRIEND_ID from FRIENDSLIST where USER_ID = " + userId + ") and FULLNAME like '%" + searchUsername.getText().toString() + "%' and ID not in (select RECEIVER_ID from FRIEND_REQUESTS where SENDER_ID = " + userId + ")");
while (resultat.next()) {
arrayListUserData.add(new UserData(resultat.getString("FULLNAME"), resultat.getString("IMAGE"), resultat.getString("ID"), userId));
}
} catch (SQLException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
initRecycleView();
}
});
}
private void initRecycleView() {
RecyclerView recyclerView = findViewById(R.id.recyclerView);
SendFriendRequestAdapter adapter = new SendFriendRequestAdapter(arrayListUserData, this);
recyclerView.setAdapter(adapter);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
}
}
I think it's the RecyclerView in your XML that needs to be adjusted at android:layout_height = "0dp"
<androidx.recyclerview.widget.RecyclerView
android:id="#+id/recyclerView"
android:layout_width="match_parent"
android:layout_height="0dp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintTop_toBottomOf="#+id/linearlayout"/>

TextView in RecyclerView is not showed up

I've been trying to fix my code for a long time. I looked so so many places to find a solution but no avail. If you look at my code and show me why my TextViews in RecylerView is not showed, that'd be great.
I am trying to use WebSocket-ing and fetch data from internet. That should be displayed in the RecyclerView in a constantly updated way. Data ledgers from ripple servers are coming with a natural delay. I want to show their some aspects in RecyclerView. All TextViews can change in content, they are just to try it out.
Here is my WebSocketActivity code:
package com.example.menes.searchcode.Websocketing;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;
import com.example.menes.searchcode.R;
import com.google.gson.Gson;
import org.java_websocket.client.WebSocketClient;
import org.java_websocket.drafts.Draft;
import org.java_websocket.handshake.ServerHandshake;
import org.json.JSONObject;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
public class WebSocketActivity extends AppCompatActivity implements MyWebSocketAdapter.OnItemClickListener {
private RecyclerView webSocketRecyclerView;// = findViewById(R.id.myRecyclerView);
private MyWebSocketAdapter myWebSocketAdapter;
List<LedgerResult> adapterLedgerResultList = new ArrayList<>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.websocket_and_button_thing);
Button startWebsocketButton = findViewById(R.id.startButton);
final Button stopWebSocketButton = findViewById(R.id.stopButton);
startWebsocketButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
try {
if(adapterLedgerResultList.size() == 0)
Toast.makeText(WebSocketActivity.this,"Yes it is empty!, nice.",Toast.LENGTH_SHORT).show();
myWebSocketAdapter = new MyWebSocketAdapter(WebSocketActivity.this, adapterLedgerResultList);
webSocketRecyclerView = findViewById(R.id.myRecyclerView);
webSocketRecyclerView.setLayoutManager(new LinearLayoutManager(getApplicationContext()));
webSocketRecyclerView.setAdapter(myWebSocketAdapter);
final MySimpleClient c = new MySimpleClient( new URI( "wss://s2.ripple.com:443" ));
c.connect();
stopWebSocketButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
c.close();
}
});
} catch (URISyntaxException e){
e.printStackTrace();
Toast.makeText(WebSocketActivity.this,"URISyntaxException occurred. Try again!",Toast.LENGTH_SHORT).show();
}
}
});
}
public void bindIt () {
//webSocketRecyclerView.setLayoutManager(new LinearLayoutManager(getApplicationContext()));
myWebSocketAdapter.setOnItemClickListener(this);
webSocketRecyclerView.setHasFixedSize(true);
//webSocketRecyclerView.setAdapter(myWebSocketAdapter);
}
#Override
public void onItemClick(int position) {
Intent intent = new Intent(this, LedgerDisplayActivity.class);
intent.putExtra("id", adapterLedgerResultList.get(position).getLedger_hash());
startActivity(intent);
//Toast.makeText(this,"Hey there, you onClicked!", Toast.LENGTH_SHORT).show();
}
public List<LedgerResult> addToadapterLedgerResultList (LedgerResult ledgerResult1){
if(adapterLedgerResultList.size() != 0) {
adapterLedgerResultList.add(ledgerResult1);
/* myWebSocketAdapter.notifyItemInserted(adapterLedgerResultList.indexOf(ledgerResult1));
webSocketRecyclerView.scrollToPosition(adapterLedgerResultList.indexOf(ledgerResult1));*/
myWebSocketAdapter.notifyItemInserted(adapterLedgerResultList.size() - 1);
//myWebSocketAdapter.notifyDataSetChanged();
webSocketRecyclerView.scrollToPosition(adapterLedgerResultList.size() - 1);
return adapterLedgerResultList;
}
else {
adapterLedgerResultList.add(ledgerResult1);
myWebSocketAdapter.notifyItemInserted(0);
//myWebSocketAdapter.notifyDataSetChanged();
return adapterLedgerResultList;
}
}
public class MySimpleClient extends WebSocketClient {
public MySimpleClient( URI serverUri , Draft draft ) {
super( serverUri, draft );
}
public MySimpleClient( URI serverURI ) {
super( serverURI );
}
public MySimpleClient( URI serverUri, Map<String, String> httpHeaders ) {
super(serverUri, httpHeaders);
}
#Override
public void onOpen( ServerHandshake handshakedata ) {
send("{\n" +
" \"id\": 1,\n" +
" \"command\": \"subscribe\",\n" +
" \"accounts\": [],\n" +
" \"streams\": [\n" +
" \"server\",\n" +
" \"ledger\"\n" +
" ]\n" +
"}");
Log.d("SearchCode", "Connection opened!");
// if you plan to refuse connection based on ip or httpfields overload: onWebsocketHandshakeReceivedAsClient
}
#Override
public void onMessage(String message) {
try {
JSONObject obj = new JSONObject(message);
Gson gson = new Gson();
LedgerResult ledgerResult = gson.fromJson(obj.toString(),LedgerResult.class);
StreamExceptionHandler lilHandler = gson.fromJson(obj.toString(),StreamExceptionHandler.class);
if(lilHandler.getBase_fee() != null){
//do nothing.
}else {
adapterLedgerResultList = addToadapterLedgerResultList(ledgerResult);
if(adapterLedgerResultList.get(0).getLedger_index() == null){
LedgerResult tmp = adapterLedgerResultList.get(0);
adapterLedgerResultList.remove(tmp);
myWebSocketAdapter.notifyItemRemoved(0);
// myWebSocketAdapter.notifyDataSetChanged();
}
else {
bindIt();
Log.d("This is obj", obj.toString());
Log.d("LedgerResult", ledgerResult.toString());
}
}
} catch (Throwable t) {
Log.e("SeachCode", "Could not parse malformed JSON: \"" + message + "\"");
}
}
#Override
public void onClose( int code, String reason, boolean remote ) {
Log.e("SearchCode: ","Connection closed by " + ( remote ? "remote peer" : "us" ) + " Code: " + code + " Reason: " + reason);
}
#Override
public void onError( Exception ex ) {
ex.printStackTrace();
}
}
}
And my adapter code MyWebSocketAdapter is here:
package com.example.menes.searchcode.Websocketing;
import android.content.Context;
import android.graphics.Color;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import com.example.menes.searchcode.R;
import java.util.List;
public class MyWebSocketAdapter extends RecyclerView.Adapter<MyWebSocketAdapter.WebSocketView> {
public interface OnItemClickListener {
void onItemClick (int position);
}
private MyWebSocketAdapter.OnItemClickListener onItemClickListener;
private Context context;
private List<LedgerResult> adapterLedgerResultList;
public MyWebSocketAdapter(Context context, List<LedgerResult> adapterLedgerResultList){
this.context = context;
this.adapterLedgerResultList = adapterLedgerResultList;
}
/*public MyWebSocketAdapter(Context context){
this.context = context;
}*/
/*public List<LedgerResult> addToadapterLedgerResultList (LedgerResult ledgerResult1){
adapterLedgerResultList.add(ledgerResult1);
if(adapterLedgerResultList.size() != 0) {
notifyItemInserted(adapterLedgerResultList.indexOf(ledgerResult1));
return adapterLedgerResultList;
}
else {
notifyItemInserted(0);
return adapterLedgerResultList;
}
}*/
public void setOnItemClickListener(MyWebSocketAdapter.OnItemClickListener onItemClickListener) {
this.onItemClickListener = onItemClickListener;
}
class WebSocketView extends RecyclerView.ViewHolder {
TextView otherThing;
TextView hashCode, textView;
public WebSocketView(View itemView) {
super(itemView);
hashCode = itemView.findViewById(R.id.hashCode);
otherThing = itemView.findViewById(R.id.otherThing);
textView = itemView.findViewById(R.id.textView);
}
}
#Override
public WebSocketView onCreateViewHolder(ViewGroup parent, int viewType) {
View layoutView = LayoutInflater.from(parent.getContext()).inflate(R.layout.in_recycler, parent, false);
return new WebSocketView(layoutView);
}
#Override
public void onBindViewHolder(WebSocketView holder, final int position) {
final WebSocketView hldr = holder;
LedgerResult row = adapterLedgerResultList.get(hldr.getAdapterPosition());
if(row.getLedger_hash() == null) {
holder.hashCode.setText("IT IS NULL");
}
else {
holder.hashCode.setText(row.getLedger_hash());
holder.hashCode.setTextColor(Color.parseColor("#239DEA"));
}
if(row.getLedger_index() == null) {
holder.otherThing.setText("IT IS NULL");
}
else {
holder.otherThing.setText(row.getLedger_index().toString());
}
if(row.getLedger_index() != null) {
String s = row.getValidated_ledgers().toString();
holder.textView.setText(s);
//holder.textView.setVisibility(View.VISIBLE);
}
holder.itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(onItemClickListener != null) {
onItemClickListener.onItemClick(hldr.getAdapterPosition());
}
}
});
}
/* #Override
public void onAttachedToRecyclerView(RecyclerView recyclerView) {
super.onAttachedToRecyclerView(recyclerView);
}*/
#Override
public int getItemCount() {
return adapterLedgerResultList.size();
}
}
My XML files which I have also checked millions of times and even re-created.
websocket_and_button_thing.xml is:
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent">
<Button
android:id="#+id/startButton"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_marginBottom="20dp"
android:layout_marginEnd="8dp"
android:layout_marginStart="8dp"
android:layout_marginTop="8dp"
android:text="Start"
app:layout_constraintBottom_toTopOf="#+id/stopButton"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.0"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/myRecyclerView"
app:layout_constraintVertical_bias="1.0" />
<Button
android:id="#+id/stopButton"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_marginBottom="4dp"
android:layout_marginEnd="8dp"
android:layout_marginStart="8dp"
android:text="Stop"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.0"
app:layout_constraintStart_toStartOf="parent" />
<android.support.v7.widget.RecyclerView
app:layoutManager="android.support.v7.widget.LinearLayoutManager"
android:id="#+id/myRecyclerView"
android:layout_width="368dp"
android:layout_height="363dp"
android:layout_marginEnd="8dp"
android:layout_marginStart="8dp"
android:layout_marginTop="4dp"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.0"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent">
</android.support.v7.widget.RecyclerView>
</android.support.constraint.ConstraintLayout>
And finally the inside-of-recyclerView code is called in-recycler.xml and it is:
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<TextView
android:id="#+id/textView"
android:layout_width="94dp"
android:layout_height="wrap_content"
android:layout_marginBottom="8dp"
android:layout_marginEnd="8dp"
android:layout_marginStart="8dp"
android:layout_marginTop="8dp"
android:gravity="center_horizontal"
android:text="TextView"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/hashCode" />
<TextView
android:id="#+id/hashCode"
android:layout_width="261dp"
android:layout_height="20dp"
android:layout_marginBottom="8dp"
android:layout_marginEnd="8dp"
android:layout_marginStart="8dp"
android:layout_marginTop="16dp"
android:text="TextView"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toStartOf="#+id/otherThing"
app:layout_constraintHorizontal_bias="0.0"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.0" />
<TextView
android:id="#+id/otherThing"
android:layout_width="0dp"
android:layout_height="20dp"
android:layout_marginBottom="8dp"
android:layout_marginEnd="16dp"
android:layout_marginTop="16dp"
android:text="TextView"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.0" />
</android.support.constraint.ConstraintLayout>
Anyone is able to come up with a solution why TextViews are not showed up?
From the LOG records I can get all the data From debugging, my lists are working correct as well.
Note: I used the StreamExceptionHandler class to differentiate between two stream outcomes. One is useful to me, other is not and that's why I do not do anything if I catch anything.
Plus, my custom classes are working correctly since my lists seems to be well working.
AFTER EDIT:
I changed the WebSocketActivity and adapter as such. No so much changed. But now, again strangely, I am gettin all the data. It is added to RecyclerView too, but it does not show itself until I try to scroll manually. Plus, whenever a new data is arrived, RecyclerView completely disappears, then if I scroll again, it gets back with the updated data. ANY SOLUTION after update?
Do you see this line in MyWebSocketAdapter:
holder.textView.setVisibility(View.INVISIBLE);
I guess, I found it. Since I changed the systematic and the code itself I cannot post the exact code to solve it but the key is overriding the runOnUiThread function within the button click. And you should change the RecyclerView binding and manager sets as well. Do it in a different place.
To override the runOnUiThread in an anonymous (inner) class, use this:
MainActivity.this.runOnUiThread(new Runnable() {
#Override
public void run() {
}
});
Hope this helps the future visitors.

Custom EditTextDialog is broken in Android 4.3

I'm currently working on an application and I have and unwanted behavior on my custom EditText Dialog. Here's the XML code
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent">
<android.support.design.widget.TextInputLayout
android:layout_width="match_parent"
android:layout_height="wrap_content" >
<EditText
android:id="#+id/editText_dialog"
android:layout_width="fill_parent"
android:inputType="textCapSentences"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:textAppearance="?android:attr/textAppearanceMedium"/>
</android.support.design.widget.TextInputLayout>
<RelativeLayout
android:layout_marginTop="10dp"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/close_dialog"
android:id="#+id/cancel_dialog"
android:textSize="20sp"
android:layout_margin="20dp"
android:layout_gravity="right"
android:layout_toLeftOf="#+id/valid_dialog" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/validate_dialog"
android:id="#+id/valid_dialog"
android:textSize="20sp"
android:layout_margin="20dp"
android:layout_gravity="right"
android:textColor="#android:color/holo_blue_light"
android:layout_alignParentRight="true" />
</RelativeLayout>S7
</LinearLayout>
And here is the class for the TextEditDialog
package com.fitme.staffbooker;
import android.app.Dialog;
import android.content.Context;
import android.os.Bundle;
import android.text.InputType;
import android.view.View;
import android.widget.EditText;
import android.widget.NumberPicker;
public class EditTextDialog extends Dialog {
private EditText editText;
public boolean dismissed = false;
public EditTextDialog(Context context, String title) {
super(context, android.R.style.Theme_Holo_Light_Dialog);
setTitle(title);
}
#Override
protected void onCreate(final Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.edit_text_dialog);
editText = (EditText) findViewById(R.id.editText_dialog);
findViewById(R.id.valid_dialog).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
dismissed = true;
dismiss();
}
});
findViewById(R.id.cancel_dialog).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
cancel();
}
});
}
public void setHint(String str) {
editText.setHint(str);
}
public void setText(String str) {
editText.setText(str);
}
public void setInputType(int type) {
editText.setInputType(type);
}
public String getValue() {
return editText.getText().toString();
}
}
Here's the output i'm having on my Galaxy S7 Edge :
But when I'm running my app on a Galaxy SIII Emulator it seems broken :
It seems that this only happens on 4.3 and below. I have no idea what is happening.

Android text to speech not working on mobile

i am having problem in text to speech. have this code in java class
package com.techblogon.loginexample;
import java.util.Locale;
import android.os.Bundle;
import android.app.Activity;
import android.speech.tts.TextToSpeech;
import android.speech.tts.TextToSpeech.OnInitListener;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.EditText;
import android.widget.Toast;
public class listenActivity extends Activity implements OnClickListener, OnInitListener {
private TextToSpeech tts;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.categories);
tts = new TextToSpeech(this, this);
findViewById(R.id.button1).setOnClickListener(this);
}
#Override
public void onClick(View v) {
if (tts!=null) {
String text = ((EditText)findViewById(R.id.editText1)).getText().toString();
if (text!=null) {
if (!tts.isSpeaking()) {
tts.speak(text, TextToSpeech.QUEUE_FLUSH, null);
}
}
}
}
#Override
public void onInit(int code) {
if (code==TextToSpeech.SUCCESS) {
tts.setLanguage(Locale.getDefault());
} else {
tts = null;
Toast.makeText(this, "Failed to initialize TTS engine.", Toast.LENGTH_SHORT).show();
}
}
#Override
protected void onDestroy() {
if (tts!=null) {
tts.stop();
tts.shutdown();
}
super.onDestroy();
}
}
and xml file has this code
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".listenActivity" >
<TextView
android:id="#+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="TTS Demonstration" />
<Button
android:id="#+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/editText1"
android:layout_centerHorizontal="true"
android:layout_marginTop="43dp"
android:text="Say It" />
<EditText
android:id="#+id/editText1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/textView1"
android:layout_centerHorizontal="true"
android:layout_marginTop="77dp"
android:ems="10"
android:text="Hello world!" />
</RelativeLayout>
but issue is when i click button no sound heard on my mobile. does i need any permission for that
any help
Many thanks

onOptionsItemClick or onMenuItemClick not being called

(Very first thing i want to make clear is that i am COMPLETELY NEWBIE, very beginner in android, in fact in programming/coding!)
The menu is referred in onCreateOptionMenu and the calling method is also onOptionsItemSelected to open up menu but the method for each option/item is set as onMenuItemClick and onMenuItemLongClick which is ideal for context menu options/items!
The problem is onMenuItemClick have input parameters as (View v, int position) and I cannot change it to only (View v) or to (MenuItem item).
What I want is clicking on each item of menu should bring out new activity!
I also tried putting all my switch-case-break statements to onOptionsItemSelected method but it is still not working!
I also tried in fragment class, setHasOptionsMenu (true); but it did not work!
onMenuItemClick doesn't get called
(Deprecated) Fragment onOptionsItemSelected not being called
Below is the activity_main_menu.xml layout
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:background="#color/menu_item_background">
<include layout="#layout/toolbar" />
<FrameLayout
android:id="#+id/container"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</LinearLayout>
Below is the fragment_main.xml layout
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.example.android.coffeeshop.MainFragment">
<!-- TODO: Update blank fragment layout -->
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
android:background="#color/menu_item_background">
<EditText
android:id="#+id/username"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="16dp"
android:cursorVisible="true"
android:hint="#string/EditTextHint"
android:inputType="textNoSuggestions" />
<EditText
android:id="#+id/usercontact"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="16dp"
android:cursorVisible="true"
android:hint="#string/usercontactHint"
android:inputType="textNoSuggestions" />
<EditText
android:id="#+id/useremail"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="16dp"
android:cursorVisible="true"
android:hint="#string/useremailHint"
android:inputType="textEmailAddress" />
<TextView
style="#style/HeaderTextStyle"
android:layout_marginTop="16dp"
android:text="#string/Toppings" />
<CheckBox
android:id="#+id/whippedCreamcheckbox"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="16dp"
android:paddingEnd="24dp"
android:paddingLeft="24dp"
android:paddingStart="24dp"
android:text="#string/WhippedCream"
android:textSize="16sp" />
<CheckBox
android:id="#+id/Chocolatebox"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="16dp"
android:paddingEnd="24dp"
android:paddingLeft="24dp"
android:paddingStart="24dp"
android:text="#string/Chocolate"
android:textSize="16sp" />
<TextView
style="#style/HeaderTextStyle"
android:layout_marginTop="16dp"
android:text="#string/quantity" />
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="horizontal">
<Button
android:layout_width="48dp"
android:layout_height="48dp"
android:layout_marginTop="16dp"
android:onClick="decrement"
android:text="#string/minus" />
<TextView
android:id="#+id/quantity_text_view"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="8dp"
android:layout_marginRight="8dp"
android:layout_marginTop="16dp"
android:text="#string/Zero"
android:textColor="#android:color/black"
android:textSize="20sp" />
<Button
android:layout_width="48dp"
android:layout_height="48dp"
android:layout_marginTop="16dp"
android:onClick="increment"
android:text="#string/plus" />
</LinearLayout>
<TextView
style="#style/HeaderTextStyle"
android:layout_marginTop="16dp"
android:text="#string/OrderSummary" />
<TextView
android:id="#+id/order_summary_text_view"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="16dp"
android:text="#string/Price"
android:textColor="#android:color/black"
android:textSize="20sp" />
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="horizontal">
<Button
android:id="#+id/orderButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="16dp"
android:onClick="submitOrder"
android:text="#string/Order" />
<Button
android:id="#+id/placeOrder"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="16dp"
android:layout_marginStart="16dp"
android:layout_marginTop="16dp"
android:onClick="placeOrder"
android:text="#string/PlaceOrder" />
</LinearLayout>
</LinearLayout>
</ScrollView>
Below is the MainMenu.java class file from where i am trying to handle fragment menu!
package com.example.android.coffeeshop5profile;
import android.app.ProgressDialog;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.ActionMenuView;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import com.yalantis.contextmenu.lib.ContextMenuDialogFragment;
import com.yalantis.contextmenu.lib.MenuObject;
import com.yalantis.contextmenu.lib.MenuParams;
import com.yalantis.contextmenu.lib.interfaces.OnMenuItemLongClickListener;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
/**
* This app displays an order form to order coffee.
*/
public class MainMenu extends AppCompatActivity implements ActionMenuView.OnMenuItemClickListener, OnMenuItemLongClickListener {
private FragmentManager fragmentManager;
private ContextMenuDialogFragment mMenuDialogFragment;
int quantity = 1;
int price = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main_menu);
fragmentManager = getSupportFragmentManager();
initToolbar();
initMenuFragment();
addFragment(new MainFragment(), true, R.id.container);
}
private void initMenuFragment() {
MenuParams menuParams = new MenuParams();
menuParams.setActionBarSize((int) getResources().getDimension(R.dimen.tool_bar_height));
menuParams.setMenuObjects(getMenuObjects());
menuParams.setClosableOutside(false);
mMenuDialogFragment = ContextMenuDialogFragment.newInstance(menuParams);
mMenuDialogFragment.setItemLongClickListener(this);
}
private List<MenuObject> getMenuObjects() {
List<MenuObject> menuObjects = new ArrayList<>();
MenuObject close = new MenuObject();
close.setResource(R.drawable.icn_close);
MenuObject send = new MenuObject("Send message");
send.setResource(R.drawable.icn_1);
MenuObject like = new MenuObject("Like profile");
Bitmap b = BitmapFactory.decodeResource(getResources(), R.drawable.icn_2);
like.setBitmap(b);
MenuObject addFr = new MenuObject("Add to friends");
BitmapDrawable bd = new BitmapDrawable(getResources(),
BitmapFactory.decodeResource(getResources(), R.drawable.icn_3));
addFr.setDrawable(bd);
MenuObject addFav = new MenuObject("Add to favorites");
addFav.setResource(R.drawable.icn_4);
MenuObject block = new MenuObject("Block user");
block.setResource(R.drawable.icn_5);
menuObjects.add(close);
menuObjects.add(send);
menuObjects.add(like);
menuObjects.add(addFr);
menuObjects.add(addFav);
menuObjects.add(block);
return menuObjects;
}
private void initToolbar() {
Toolbar mToolbar = (Toolbar) findViewById(R.id.toolbar);
TextView mToolBarTextView = (TextView) findViewById(R.id.text_view_toolbar_title);
setSupportActionBar(mToolbar);
getSupportActionBar().setHomeButtonEnabled(true);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setDisplayShowTitleEnabled(false);
mToolbar.setNavigationIcon(R.drawable.btn_back);
mToolbar.setNavigationOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
onBackPressed();
}
});
mToolBarTextView.setText(R.string.title_text);
}
protected void addFragment(Fragment fragment, boolean addToBackStack, int containerId) {
invalidateOptionsMenu();
String backStackName = fragment.getClass().getName();
boolean fragmentPopped = fragmentManager.popBackStackImmediate(backStackName, 0);
if (!fragmentPopped) {
FragmentTransaction transaction = fragmentManager.beginTransaction();
transaction.add(containerId, fragment, backStackName)
.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN);
if (addToBackStack)
transaction.addToBackStack(backStackName);
transaction.commit();
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.context_main_menu, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.context_menu:
if (fragmentManager.findFragmentByTag(ContextMenuDialogFragment.TAG) == null) {
mMenuDialogFragment.show(fragmentManager, ContextMenuDialogFragment.TAG);
}
break;
case R.drawable.icn_3:
Intent userProfileIntent = new Intent(MainMenu.this, UserProfile.class);
MainMenu.this.startActivity(userProfileIntent);
break;
case R.drawable.icn_4:
Intent wishListIntent = new Intent(MainMenu.this, UserProfile.class);
MainMenu.this.startActivity(wishListIntent);
break;
}
return false; //Turning this true or to super.OnOptionsItemSelected did nothing!
}
#Override
public void onBackPressed() {
if (mMenuDialogFragment != null && mMenuDialogFragment.isAdded()) {
mMenuDialogFragment.dismiss();
} else {
finish();
}
}
#Override
public boolean onMenuItemClick(MenuItem item) {
switch (item.getItemId()){
case R.drawable.icn_3:
Intent userProfileIntent = new Intent(MainMenu.this, UserProfile.class);
MainMenu.this.startActivity(userProfileIntent);
break;
case R.drawable.icn_4:
Intent wishListIntent = new Intent(MainMenu.this, UserProfile.class);
MainMenu.this.startActivity(wishListIntent);
break;
} return true;
}
#Override
public void onMenuItemLongClick(View clickedView, int position) {
Toast.makeText(this, "Long clicked on position: " + position, Toast.LENGTH_SHORT).show();
}
public void submitOrder(View view) {
String orderSummaryString = createOrderSummary(quantity);
displayMessage(orderSummaryString);
}
public void placeOrder(View view) {
TextView useremail = (TextView) findViewById(R.id.useremail);
String useremailString = useremail.getText().toString();
String orderSummaryString = createOrderSummary(quantity);
sendMail(useremailString, "Coffee Order By: " + useremailString, orderSummaryString);
}
private void sendMail(String email, String subject, String messageBody) {
Session session = createSessionObject();
try {
Message message = createMessage(email, subject, messageBody, session);
new SendMailTask().execute(message);
} catch (MessagingException | UnsupportedEncodingException e) {
e.printStackTrace();
}
}
private Message createMessage(String email, String subject, String messageBody, Session session)
throws MessagingException, UnsupportedEncodingException {
Message message = new MimeMessage(session);
message.setFrom(new InternetAddress("clientaddress#gmail.com", "Coffee Order By"));
message.addRecipient(Message.RecipientType.TO, new InternetAddress(email, email));
message.setSubject(subject);
message.setText(messageBody);
return message;
}
private Session createSessionObject() {
Properties properties = new Properties();
properties.put("mail.smtp.auth", "true");
properties.put("mail.smtp.starttls.enable", "true");
properties.put("mail.smtp.host", "smtp.gmail.com");
properties.put("mail.smtp.port", "587");
return Session.getInstance(properties, new javax.mail.Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication("clientaddress#gmail.com", "************");
}
});
}
public class SendMailTask extends AsyncTask<Message, Void, Void> {
private ProgressDialog progressDialog;
#Override
protected void onPreExecute() {
super.onPreExecute();
progressDialog = ProgressDialog.show(MainMenu.this, "Please wait", "Sending mail", true, false);
}
#Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
progressDialog.dismiss();
}
#Override
public Void doInBackground(Message... messages) {
try {
Transport.send(messages[0]);
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
}
/**
* This method is called when the plus button is clicked.
*/
public void increment(View view) {
if (quantity < 100) {
quantity = quantity + 1;
displayQuantity(quantity);
} else {
Toast.makeText(this, "You have reached maximum numbers of coffees to be allowed!", Toast.LENGTH_SHORT).show();
}
}
/**
* This method is called when the minus button is clicked.
*/
public void decrement(View view) {
if (quantity >= 2) {
quantity = quantity - 1;
displayQuantity(quantity);
} else {
Toast.makeText(this, "You can not place order in negative number!", Toast.LENGTH_SHORT).show();
}
}
public String createOrderSummary(int quantity) {
CheckBox whippedCreamCheckbox = (CheckBox) findViewById(R.id.whippedCreamcheckbox);
boolean hasWhippedCream = whippedCreamCheckbox.isChecked();
CheckBox chocolatebox = (CheckBox) findViewById(R.id.Chocolatebox);
boolean hasChocolate = chocolatebox.isChecked();
price = 5;
if (hasWhippedCream) {
price = price + 1;
}
if (hasChocolate) {
price = price + 2;
}
int finalPrice = quantity * price;
EditText usernameTextView = (EditText) findViewById(R.id.username);
String usernameString = usernameTextView.getText().toString();
EditText usercontact = (EditText) findViewById(R.id.usercontact);
String userContactString = usercontact.getText().toString();
EditText useremail = (EditText) findViewById(R.id.useremail);
String userEmailString = useremail.getText().toString();
String OrderSummary = getString(R.string.username) + ": " + usernameString;
OrderSummary += "\n" + getString(R.string.ContactNumber) + " " + userContactString;
OrderSummary += "\n" + getString(R.string.eAddress) + " " + userEmailString;
OrderSummary += "\n" + getString(R.string.AddedWhippedCream) + " " + hasWhippedCream;
OrderSummary += "\n" + getString(R.string.AddedChocolate) + " " + hasChocolate;
OrderSummary += "\n" + getString(R.string.quantity) + ": " + quantity;
OrderSummary += "\n" + getString(R.string.totalprice) + finalPrice;
OrderSummary += "\n" + getString(R.string.thankyou);
return OrderSummary;
}
/**
* This method displays the given quantity value on the screen.
*/
public void displayQuantity(int number) {
TextView quantityTextView = (TextView) findViewById(
R.id.quantity_text_view);
quantityTextView.setText(String.format("%d", number));
}
/**
* This method displays the given text on the screen.
*/
public void displayMessage(String message) {
TextView orderSummaryTextView = (TextView) findViewById(R.id.order_summary_text_view);
orderSummaryTextView.setText(message);
}
}
Below is the MainFragment.java class file
package com.example.android.coffeeshop5profile;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
public class MainFragment extends Fragment {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_main, container, false);
setHasOptionsMenu(true);
setMenuVisibility(false);
return rootView;
}
}
Following is the Activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/main_layout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#color/blue_grey_700"
android:orientation="vertical"
android:weightSum="4"
tools:context=".legacy.MainActivity">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="3"
android:gravity="center_vertical"
android:orientation="vertical">
<ImageView
android:id="#+id/google_icon"
android:layout_width="48dp"
android:layout_height="48dp"
android:layout_gravity="center"
android:layout_marginBottom="10dp"
android:contentDescription="#string/desc_google_icon"
android:src="#drawable/googleg_color" />
<TextView
android:id="#+id/title_text"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginBottom="10dp"
android:layout_gravity="center"
android:text="#string/title_text"
android:textColor="#android:color/white"
android:textSize="36sp" />
<TextView
android:id="#+id/status"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:text="#string/signed_out"
android:textColor="#android:color/white"
android:textSize="14sp" />
<TextView
android:id="#+id/detail"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:fadeScrollbars="true"
android:gravity="center"
android:maxLines="5"
android:padding="10dp"
android:scrollbars="vertical"
android:textColor="#android:color/white"
android:textSize="14sp" />
</LinearLayout>
<RelativeLayout
android:layout_width="fill_parent"
android:layout_height="0dp"
android:layout_weight="1"
android:background="#color/blue_grey_900">
<com.google.android.gms.common.SignInButton
android:id="#+id/sign_in_button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:visibility="visible"
tools:visibility="gone" />
<LinearLayout
android:id="#+id/sign_out_and_disconnect"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:orientation="horizontal"
android:paddingLeft="16dp"
android:paddingRight="16dp"
android:visibility="gone"
tools:visibility="visible">
<Button
android:id="#+id/sign_out_button"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="#string/sign_out"
android:theme="#style/ThemeOverlay.MyDarkButton" />
<Button
android:id="#+id/disconnect_button"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="#string/disconnect"
android:theme="#style/ThemeOverlay.MyDarkButton" />
<Button
android:id="#+id/secondpage"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="#string/secondpage"
android:theme="#style/ThemeOverlay.MyDarkButton" />
</LinearLayout>
</RelativeLayout>
</LinearLayout>
below is the res/menu/context_main_menu.xml file
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto">
<item
android:id="#+id/context_menu"
android:title="#string/context_menu"
android:icon="#drawable/btn_add"
android:orderInCategory="100"
app:showAsAction="always" />
</menu>
...unfortunately, 30000 characters limit has been reached so i cant upload mainActivity.java file!
Kindly help!
Best regards,
sagar
try this code on
Change the following code
onMenuItemClick(MenuItem item)
to
onMenuItemClick(View clickedView, int position)
like this
`#override
public void onMenuItemClick(View clickedView, int position) {
switch (position) {
case 1:
startActivity(new Intent(MainActivity.this, UserProfile.class));
break;
case 2:
startActivity(new Intent(MainActivity.this, UserProfile.class));
break;
}
}`
i hope this help you
If onOptionsItemSelected() method is not called in fragment then just make sure you return false from the onOptionsItemSelected() method of Activity.

Categories

Resources