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.
Related
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"/>
I'm developing wordpress android app which loads Wordpress post data in android webview. I'm using retrofit & JSON API to fetch data from my Wordpress site. My app worked fine in android API LEVEL 26 but the problem is I need API 28+ to upload to google play store. I migrated to androidx API LEVEL 29. post were not getting loaded showing ERR_CLEARTEXT_NOT_PERMITTED so I used "android:usesCleartextTraffic=true" post was loading but the problem is HTML entities like –,“,’ etc failed to decode and decoded as & and remaining lines of the post are not loaded after this. I dint use "android:usesCleartextTraffic=true" in API LEVEL 26 but it works fine without any error. I'm searching a solution for my problem I didn't find satisfying answers anywhere. I'm stuck at this point. So I'm trying alternative method for "android:usesCleartextTraffic=true". I have "text to speech" function in my app its working absolutely fine I mean its reading entire post which is not visible in android webview. Kindly suggest. Please find the code for your reference.
WEBVIEW SCREESHOT
this is my postdetails activity
Postdetails.java
package ak.wp.meto.activity;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import com.google.android.material.floatingactionbutton.FloatingActionButton;
import androidx.fragment.app.FragmentManager;
import androidx.core.content.ContextCompat;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.text.Html;
import android.view.MenuItem;
import android.view.View;
import android.webkit.WebView;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import com.bumptech.glide.Glide;
import ak.wp.meto.R;
import ak.wp.meto.adapters.CommentsAdapter;
import ak.wp.meto.api.http.ApiUtils;
import ak.wp.meto.api.models.posts.post.CommentsAndReplies;
import ak.wp.meto.api.models.posts.post.PostDetails;
import ak.wp.meto.api.params.HttpParams;
import ak.wp.meto.data.constant.AppConstant;
import ak.wp.meto.data.sqlite.FavouriteDbController;
import ak.wp.meto.fragment.WriteACommentFragment;
import ak.wp.meto.listeners.ListItemClickListener;
import ak.wp.meto.models.FavouriteModel;
import ak.wp.meto.utility.ActivityUtils;
import ak.wp.meto.utility.AppUtils;
import ak.wp.meto.utility.TtsEngine;
import ak.wp.meto.webengine.WebEngine;
import ak.wp.meto.webengine.WebListener;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
public class PostDetailsActivity extends BaseActivity implements WriteACommentFragment.OnCompleteListener {
// Variables
private Activity mActivity;
private Context mContext;
// init views
private RelativeLayout lytPostDetailsView, lytCommentDetails;
private int clickedPostId;
private ImageView imgPost;
private TextView tvPostTitle, tvPostAuthor, tvPostDate, tvCommnentList;
private WebView webView;
private FloatingActionButton fabWriteAComment;
private ImageButton imgBtnSpeaker, imgBtnFav, imgBtnShare;
private PostDetails model = null;
// Favourites view
private List<FavouriteModel> favouriteList;
private FavouriteDbController favouriteDbController;
private boolean isFavourite = false;
// Comments view
private List<CommentsAndReplies> commentList;
private List<CommentsAndReplies> zeroParentComments;
List<CommentsAndReplies> onlyThreeComments;
private int mPerPage = 5;
private RecyclerView rvComments;
private CommentsAdapter commentsAdapter = null;
// Text to speech
private TtsEngine ttsEngine;
private boolean isTtsPlaying = false;
private String ttsText;
private WebEngine webEngine;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
initVar();
initView();
initFunctionality();
initListener();
}
private void initVar() {
mActivity = PostDetailsActivity.this;
mContext = mActivity.getApplicationContext();
// Favourites view
favouriteList = new ArrayList<>();
// Comments view
commentList = new ArrayList<>();
zeroParentComments = new ArrayList<>();
onlyThreeComments = new ArrayList<>();
Intent intent = getIntent();
if (intent != null) {
clickedPostId = getIntent().getIntExtra(AppConstant.BUNDLE_KEY_POST_ID, 0);
}
}
private void initView() {
setContentView(R.layout.activity_post_details);
lytPostDetailsView = (RelativeLayout) findViewById(R.id.lyt_post_details);
lytCommentDetails = (RelativeLayout) findViewById(R.id.lyt_comment_list);
//lytParentView.setVisibility(View.GONE);
imgPost = (ImageView) findViewById(R.id.post_img);
tvPostTitle = (TextView) findViewById(R.id.title_text);
tvPostAuthor = (TextView) findViewById(R.id.post_author);
tvPostDate = (TextView) findViewById(R.id.date_text);
imgBtnSpeaker = (ImageButton) findViewById(R.id.imgBtnSpeaker);
imgBtnFav = (ImageButton) findViewById(R.id.imgBtnFavourite);
imgBtnShare = (ImageButton) findViewById(R.id.imgBtnShare);
initWebEngine();
tvCommnentList = (TextView) findViewById(R.id.comment_count);
fabWriteAComment = (FloatingActionButton) findViewById(R.id.fab_new_comment);
rvComments = (RecyclerView) findViewById(R.id.rvComments);
rvComments.setLayoutManager(new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false));
initLoader();
initToolbar();
enableBackButton();
}
public void initWebEngine() {
webView = (WebView) findViewById(R.id.web_view);
webEngine = new WebEngine(webView, mActivity);
webEngine.initWebView();
webEngine.initListeners(new WebListener() {
#Override
public void onStart() {
initLoader();
}
#Override
public void onLoaded() {
hideLoader();
}
#Override
public void onProgress(int progress) {
}
#Override
public void onNetworkError() {
showEmptyView();
}
#Override
public void onPageTitle(String title) {
}
});
}
private void initFunctionality() {
favouriteDbController = new FavouriteDbController(mContext);
favouriteList.addAll(favouriteDbController.getAllData());
for (int i = 0; i < favouriteList.size(); i++) {
if (favouriteList.get(i).getPostId() == clickedPostId) {
isFavourite = true;
break;
}
}
ttsEngine = new TtsEngine(mActivity);
commentsAdapter = new CommentsAdapter(mActivity, (ArrayList) commentList, (ArrayList) onlyThreeComments);
rvComments.setAdapter(commentsAdapter);
showLoader();
loadPostDetails();
// show full-screen ads
// AdUtils.getInstance(mContext).showFullScreenAd();
}
public void setFavImage() {
if (isFavourite) {
imgBtnFav.setImageDrawable(ContextCompat.getDrawable(mActivity, R.drawable.ic_book));
} else {
imgBtnFav.setImageDrawable(ContextCompat.getDrawable(mActivity, R.drawable.ic_un_book));
}
}
public void initListener() {
imgBtnSpeaker.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (model != null) {
toggleTtsPlay();
}
}
});
imgBtnFav.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (model != null) {
isFavourite = !isFavourite;
if (isFavourite) {
String imgUrl = null;
if (model.getEmbedded().getWpFeaturedMedias().size() >= 1) {
imgUrl = model.getEmbedded().getWpFeaturedMedias().get(0).getMediaDetails().getSizes().getFullSize().getSourceUrl();
}
favouriteDbController.insertData(
model.getID().intValue(),
imgUrl,
model.getTitle().getRendered(),
model.getOldDate(),
model.getEmbedded().getWpTerms().get(0).get(0).getName()
);
} else {
favouriteDbController.deleteFav(clickedPostId);
}
setFavImage();
}
}
});
imgBtnShare.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (model != null) {
Intent sendIntent = new Intent();
sendIntent.setAction(Intent.ACTION_SEND);
sendIntent.putExtra(Intent.EXTRA_TEXT, model.getPageUrl());
sendIntent.setType("text/plain");
startActivity(Intent.createChooser(sendIntent, getResources().getText(R.string.send_to)));
}
}
});
commentsAdapter.setItemClickListener(new ListItemClickListener() {
#Override
public void onItemClick(int position, View view) {
int id = view.getId();
CommentsAndReplies clickedComment = zeroParentComments.get(position);
switch (id) {
case R.id.list_item:
ActivityUtils.getInstance().invokeCommentDetails(mActivity, CommentDetailsActivity.class, (ArrayList) commentList, clickedPostId, clickedComment, false, false);
break;
case R.id.reply_text:
ActivityUtils.getInstance().invokeCommentDetails(mActivity, CommentDetailsActivity.class, (ArrayList) commentList, clickedPostId, clickedComment, true, false);
break;
default:
break;
}
}
});
tvCommnentList.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
ActivityUtils.getInstance().invokeCommentList(mActivity,
CommentListActivity.class,
(ArrayList) commentList,
(ArrayList) zeroParentComments,
clickedPostId,
false);
}
});
fabWriteAComment.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
FragmentManager manager = getSupportFragmentManager();
WriteACommentFragment dialog = WriteACommentFragment.newInstance(clickedPostId, AppConstant.THIS_IS_COMMENT);
dialog.show(manager, AppConstant.BUNDLE_KEY_DIALOG_FRAGMENT);
}
});
}
public void loadPostDetails() {
ApiUtils.getApiInterface().getPostDetails(clickedPostId).enqueue(new Callback<PostDetails>() {
#Override
public void onResponse(Call<PostDetails> call, Response<PostDetails> response) {
if (response.isSuccessful()) {
// bind data
model = response.body();
PostDetails m = model;
// visible parent view
lytPostDetailsView.setVisibility(View.VISIBLE);
// visible comments button
fabWriteAComment.setVisibility(View.VISIBLE);
loadCommentsAndReplies(model.getLinks().getRepliesList().get(0).getHref());
setFavImage();
tvPostTitle.setText(Html.fromHtml(model.getTitle().getRendered()));
String imgUrl = null;
if (model.getEmbedded().getWpFeaturedMedias().size() > 0) {
if (model.getEmbedded().getWpFeaturedMedias().get(0).getMediaDetails() != null) {
if (model.getEmbedded().getWpFeaturedMedias().get(0).getMediaDetails().getSizes().getFullSize().getSourceUrl() != null) {
imgUrl = model.getEmbedded().getWpFeaturedMedias().get(0).getMediaDetails().getSizes().getFullSize().getSourceUrl();
}
}
}
if (imgUrl != null) {
Glide.with(getApplicationContext())
.load(imgUrl)
.into(imgPost);
}
String author = null;
if (model.getEmbedded().getAuthors().size() >= 1) {
author = model.getEmbedded().getAuthors().get(0).getName();
}
if (author == null) {
author = getString(R.string.admin);
}
tvPostAuthor.setText(Html.fromHtml(author));
String oldDate = model.getOldDate();
String newDate = AppUtils.getFormattedDate(oldDate);
if (newDate != null) {
tvPostDate.setText(Html.fromHtml(newDate));
}
String contentText = model.getContent().getRendered();
ttsText = new StringBuilder(Html.fromHtml(model.getTitle().getRendered())).append(AppConstant.DOT).append(Html.fromHtml(model.getContent().getRendered())).toString();
webView.loadData(contentText, "text/html", "UTF-8"); //comment
contentText = new StringBuilder().append(AppConstant.CSS_PROPERTIES).append(contentText).toString();
webEngine.loadHtml(contentText);
} else {
showEmptyView();
}
}
#Override
public void onFailure(Call<PostDetails> call, Throwable t) {
t.printStackTrace();
// hide common loader
hideLoader();
// show empty view
showEmptyView();
}
});
}
public void loadCommentsAndReplies(final String commentsAndRepliesLink) {
ApiUtils.getApiInterface().getCommentsAndReplies(commentsAndRepliesLink, mPerPage).enqueue(new Callback<List<CommentsAndReplies>>() {
#Override
public void onResponse(Call<List<CommentsAndReplies>> call, Response<List<CommentsAndReplies>> response) {
if (response.isSuccessful()) {
int totalItems = Integer.parseInt(response.headers().get(HttpParams.HEADER_TOTAL_ITEM));
int totalPages = Integer.parseInt(response.headers().get(HttpParams.HEADER_TOTAL_PAGE));
if (totalPages > 1) {
mPerPage = mPerPage * totalPages;
loadCommentsAndReplies(commentsAndRepliesLink);
} else {
if (!commentList.isEmpty() || !zeroParentComments.isEmpty() || !onlyThreeComments.isEmpty()) {
commentList.clear();
zeroParentComments.clear();
onlyThreeComments.clear();
}
commentList.addAll(response.body());
lytCommentDetails.setVisibility(View.VISIBLE);
if (commentList.size() > 0) {
for (CommentsAndReplies commentsAndReplies : commentList) {
if (commentsAndReplies.getParent().intValue() == 0) {
zeroParentComments.add(commentsAndReplies);
}
}
if (zeroParentComments.size() >= 3) {
for (int i = 0; i < 3; i++) {
onlyThreeComments.add(zeroParentComments.get(i));
}
} else {
for (CommentsAndReplies commentsAndReplies : zeroParentComments) {
onlyThreeComments.add(commentsAndReplies);
}
}
commentsAdapter.notifyDataSetChanged();
tvCommnentList.setText(String.format(getString(R.string.all_comment), commentList.size()));
tvCommnentList.setClickable(true);
} else {
tvCommnentList.setClickable(false);
}
}
}
}
#Override
public void onFailure(Call<List<CommentsAndReplies>> call, Throwable t) {
showEmptyView();
t.printStackTrace();
}
});
}
private void toggleTtsPlay() {
if (isTtsPlaying) {
ttsEngine.releaseEngine();
isTtsPlaying = false;
} else {
ttsEngine.startEngine(ttsText);
isTtsPlaying = true;
}
toggleTtsView();
}
private void toggleTtsView() {
if (isTtsPlaying) {
imgBtnSpeaker.setImageDrawable(getResources().getDrawable(R.drawable.ic_speaker_stop));
} else {
imgBtnSpeaker.setImageDrawable(getResources().getDrawable(R.drawable.ic_speaker));
}
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
// Respond to the action bar's Up/Home button
case android.R.id.home:
finish();
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
public void onBackPressed() {
finish();
}
#Override
protected void onStop() {
super.onStop();
ttsEngine.releaseEngine();
}
#Override
protected void onDestroy() {
super.onDestroy();
ttsEngine.releaseEngine();
model = null;
}
#Override
protected void onResume() {
super.onResume();
if (isTtsPlaying) {
isTtsPlaying = false;
imgBtnSpeaker.setImageDrawable(getResources().getDrawable(R.drawable.ic_speaker));
}
}
#Override
public void onComplete(Boolean isCommentSuccessful, CommentsAndReplies commentsAndReplies) {
if (isCommentSuccessful) {
loadCommentsAndReplies(model.getLinks().getRepliesList().get(0).getHref());
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode != RESULT_OK) {
return;
}
if (requestCode == AppConstant.REQUEST_CODE_COMMENT) {
if (data == null) {
return;
}
boolean isCommentSuccessful = CommentListActivity.wasCommentSuccessful(data);
if (isCommentSuccessful) {
loadCommentsAndReplies(model.getLinks().getRepliesList().get(0).getHref());
}
}
}
}
activity_post_details.xml
<?xml version="1.0" encoding="utf-8"?>
<androidx.coordinatorlayout.widget.CoordinatorLayout 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"
android:background="#color/white"
android:fitsSystemWindows="true">
<com.google.android.material.appbar.AppBarLayout
android:id="#+id/app_bar_layout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:fitsSystemWindows="true"
android:theme="#style/ThemeOverlay.AppCompat.Dark.ActionBar">
<com.google.android.material.appbar.CollapsingToolbarLayout
android:id="#+id/collapsing_toolbar"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true"
app:expandedTitleMarginEnd="64dp"
app:expandedTitleMarginStart="48dp"
app:layout_scrollFlags="scroll|exitUntilCollapsed">
<ImageView
android:id="#+id/post_img"
android:layout_width="match_parent"
android:layout_height="#dimen/margin_250dp"
android:fitsSystemWindows="true"
android:scaleType="centerCrop"
android:src="#color/white"
app:layout_collapseMode="parallax" />
<androidx.appcompat.widget.Toolbar
android:id="#+id/toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
app:layout_collapseMode="pin"
app:popupTheme="#style/ThemeOverlay.AppCompat.Light">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
<ImageButton
android:id="#+id/imgBtnSpeaker"
android:layout_width="30dp"
android:layout_height="30dp"
android:layout_centerVertical="true"
android:layout_marginRight="10dp"
android:layout_toLeftOf="#id/imgBtnFavourite"
android:padding="5dp"
android:scaleType="centerInside"
android:src="#drawable/ic_speaker" />
</RelativeLayout>
</androidx.appcompat.widget.Toolbar>
</com.google.android.material.appbar.CollapsingToolbarLayout>
</com.google.android.material.appbar.AppBarLayout>
<androidx.core.widget.NestedScrollView
android:layout_width="match_parent"
android:layout_height="match_parent"
app:layout_behavior="#string/appbar_scrolling_view_behavior">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<include layout="#layout/content_post_details" />
<include layout="#layout/content_comments" />
</LinearLayout>
</androidx.core.widget.NestedScrollView>
<com.google.android.material.floatingactionbutton.FloatingActionButton
android:id="#+id/fab_new_comment"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="bottom|end"
android:layout_margin="#dimen/activity_vertical_margin"
android:src="#drawable/ic_fab"
android:visibility="gone" />
<include layout="#layout/view_common_loader" /> </androidx.coordinatorlayout.widget.CoordinatorLayout>
content_post_details.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/lyt_post_details"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#color/white"
android:visibility="gone">
<LinearLayout
android:id="#+id/li_layout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="#dimen/margin_8dp"
android:layout_marginTop="#dimen/margin_8dp"
android:orientation="horizontal"
android:weightSum="1">
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="#dimen/margin_20dp"
android:layout_weight="0.5"
android:gravity="center_vertical"
android:padding="#dimen/margin_8dp">
<ImageView
android:id="#+id/author_image"
android:layout_width="#dimen/margin_30dp"
android:layout_height="#dimen/margin_30dp"
android:background="#drawable/ic_author" />
</LinearLayout>
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="#dimen/margin_20dp"
android:layout_weight="0.5"
android:gravity="center_vertical"
android:padding="#dimen/margin_8dp">
</LinearLayout>
</LinearLayout>
<View
android:id="#+id/viewDivider"
android:layout_width="match_parent"
android:layout_height="0.7dp"
android:layout_below="#id/li_layout"
android:layout_marginLeft="#dimen/margin_15dp"
android:layout_marginRight="#dimen/margin_15dp"
android:background="#color/toolbar_boarder" />
<TextView
android:id="#+id/title_text"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="#id/viewDivider"
android:layout_margin="#dimen/margin_8dp"
android:textColor="#color/black"
android:textSize="18sp"
android:textStyle="bold"
tools:text="This is sample text do yoy know that it supports multi-line" />
<WebView
android:id="#+id/web_view"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="#id/title_text"
android:layout_margin="#dimen/margin_8dp"
android:paddingBottom="#dimen/margin_8dp" />
</RelativeLayout>
> I have used MVVM to backup my data when screen orientation changes,
> the data loads perfectly but when i set the data to the adapter class
> recylerview goes empty even when onbind and getItem count gets called.
first i thought my data not getting loaded but then i tracked the data loads and everything goes fine but recycler view shows no view inside it.
**ConsumerListActivit.java**
package com.conformiz.riderapp.Activities.ConsumersList;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.AppCompatEditText;
import androidx.appcompat.widget.Toolbar;
import androidx.lifecycle.Observer;
import androidx.lifecycle.ViewModelProviders;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.transition.Visibility;
import android.app.ProgressDialog;
import android.graphics.Color;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import com.conformiz.riderapp.Adapters.CustomerListAdapter;
import com.conformiz.riderapp.Model.CustomersList.CustomersListRootResponseData;
import com.conformiz.riderapp.Model.CustomersList.CustomersListRootResponseDataProductList;
import com.conformiz.riderapp.R;
import com.conformiz.riderapp.Utilities.SharedPreferenceUtil;
import com.facebook.shimmer.Shimmer;
import com.facebook.shimmer.ShimmerFrameLayout;
import com.google.android.material.snackbar.Snackbar;
import com.google.gson.Gson;
import java.util.ArrayList;
import java.util.List;
import android.widget.EditText;
public class ConsumerListActivity extends AppCompatActivity {
public static final String TAG = "ConsumersListActivity";
private RecyclerView rvCustomersList;
private Toolbar consumersListToolbar;
private ArrayList<CustomersListRootResponseData> customersListData = new ArrayList<CustomersListRootResponseData>();
private CustomerListAdapter customerListAdapter;
private ProgressDialog progressDialog;
private EditText etSearchCustomers;
private ShimmerFrameLayout customersListShimmer;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_consumer_list);
setFrontEnd();
final ConsumerListViewModel consumerListViewModel = ViewModelProviders.of(this).get(ConsumerListViewModel.class);
consumerListViewModel.setUserId(String.valueOf(SharedPreferenceUtil.getInstance(this).getUserId()));
consumerListViewModel.getCustomersList().observe(this, new Observer<ArrayList<CustomersListRootResponseData>>() {
#Override
public void onChanged(ArrayList<CustomersListRootResponseData> customersListRootResponseData) {
Log.d(TAG, "OnChaned: "+new Gson().toJson(customersListRootResponseData).toString());
if (customersListRootResponseData == null) {
Snackbar emptyData = Snackbar.make(findViewById(R.id.activity_consumer),
R.string.no_data_found_string, Snackbar.LENGTH_SHORT);
emptyData.show();
} else {
customersListData = customersListRootResponseData;
customerListAdapter.addDataToList(customersListData);
}
}
});
consumerListViewModel.getLoadingStatus().observe(this, new Observer<Boolean>() {
#Override
public void onChanged(Boolean aBoolean) {
if(aBoolean == true){
// showProgress();
customersListShimmer.setVisibility(View.VISIBLE);
customersListShimmer.startShimmer();
rvCustomersList.setVisibility(View.GONE);
}
else{
// hideProgress();
if(customersListShimmer.getVisibility() == View.VISIBLE) {
customersListShimmer.stopShimmer();
customersListShimmer.setVisibility(View.GONE);
rvCustomersList.setVisibility(View.VISIBLE);
}
}
}
});
}
private void setFrontEnd()
{
//Setting Shimmer Layout
customersListShimmer = findViewById(R.id.customersListShimmer);
//Setting Search Edit Text
etSearchCustomers = findViewById(R.id.etSearchClient);
etSearchCustomers.addTextChangedListener(new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
}
#Override
public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
customerListAdapter.getFilter().filter(charSequence);
}
#Override
public void afterTextChanged(Editable editable) {
}
});
//Setting tool bar
consumersListToolbar = findViewById(R.id.topToolbar);
consumersListToolbar.setTitle("Customers List");
consumersListToolbar.setTitleTextColor(Color.WHITE);
consumersListToolbar.setNavigationIcon(R.drawable.ic_back_arrow);
consumersListToolbar.setNavigationOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
onBackPressed();
}
});
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
consumersListToolbar.setElevation(10f);
}
//Setting Recycler View
rvCustomersList = findViewById(R.id.consumerListRv);
LinearLayoutManager layoutManager = new LinearLayoutManager(this, RecyclerView.VERTICAL, false);
rvCustomersList.setLayoutManager(layoutManager);
//Setting Adapter
customerListAdapter = new CustomerListAdapter(customersListData);
rvCustomersList.setAdapter(customerListAdapter);
Log.d(TAG,"Initializing the front end");
}
private void showProgress(){
progressDialog = new ProgressDialog(ConsumerListActivity.this);
progressDialog.setMessage("Getting Data....");
progressDialog.setCancelable(false);
progressDialog.show();
}
private void hideProgress(){
if(progressDialog != null){
progressDialog.dismiss();
}
progressDialog = null;
}
}
**ConsumerListAdapter.java**
package com.conformiz.riderapp.Adapters;
import android.content.Context;
import android.opengl.Visibility;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Filter;
import android.widget.Filterable;
import com.conformiz.riderapp.Model.CustomersList.CustomersListRootResponseData;
import com.conformiz.riderapp.Model.CustomersList.CustomersListRootResponseDataProductList;
import com.conformiz.riderapp.R;
import com.conformiz.riderapp.ViewHolders.CustomerListVH;
import com.conformiz.riderapp.ViewHolders.ProductsVH;
import com.conformiz.riderapp.ViewHolders.ProductsViewHolder;
import java.util.ArrayList;
import java.util.List;
import java.util.function.IntToLongFunction;
import androidx.annotation.NonNull;
import androidx.lifecycle.MutableLiveData;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
public class CustomerListAdapter extends RecyclerView.Adapter<CustomerListVH> implements Filterable {
private List<CustomersListRootResponseData> customersListData = new ArrayList<>();
private List<CustomersListRootResponseData> customersListDataFull;
private RecyclerView customersProductsRv;
Context context;
public CustomerListAdapter(List<CustomersListRootResponseData> mList) {
this.customersListData = mList;
customersListDataFull = new ArrayList<>(this.customersListData);
}
#NonNull
#Override
public CustomerListVH onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.row_assignment, parent, false);
CustomerListVH customerListVH = new CustomerListVH(view);
return customerListVH;
}
#Override
public void onBindViewHolder(#NonNull final CustomerListVH holder, final int position) {
Log.d("onbinding", "HERE");
final CustomersListRootResponseData customerData = customersListData.get(position);
//Setting Child's Adapter Class for Customers Orders Product //
// ClientsProductsPerCountListAdapter clientsProductsPerCountListAdapter = new ClientsProductsPerCountListAdapter(customerData.getProductList(), position);
// holder.getRvCustomersProducts().setAdapter(clientsProductsPerCountListAdapter);
// LinearLayoutManager layoutManager = new LinearLayoutManager(context, RecyclerView.VERTICAL, false);
// holder.getRvCustomersProducts().setLayoutManager(layoutManager);
//
holder.getTvCustomerName().setText(customerData.getFullname());
holder.getTvCustomerAddress().setText(customerData.getAddress().trim());
holder.getTvCustomerPhone().setText(customerData.getCell_no_1());
holder.getEditProductIV().setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (holder.getRvCustomersProducts().getVisibility() == View.VISIBLE) {
holder.getRvCustomersProducts().setVisibility(View.GONE);
} else {
holder.getRvCustomersProducts().setVisibility(View.VISIBLE);
}
}
}
);
}
#Override
public int getItemCount() {
return this.customersListData.size();
}
public void addDataToList(ArrayList<CustomersListRootResponseData> customersListData) {
if (customersListData != null && customersListData.size() > 0) {
this.customersListData.clear();
this.customersListData.addAll(customersListData);
this.notifyDataSetChanged();
}
}
#Override
public Filter getFilter() {
return customersListFilter;
}
private Filter customersListFilter = new Filter() {
#Override
protected FilterResults performFiltering(CharSequence charSequence) {
List<CustomersListRootResponseData> filteredList = new ArrayList<>();
if (charSequence == null || charSequence.length() == 0) {
filteredList.addAll(customersListDataFull);
} else {
String filterPattern = charSequence.toString().toLowerCase().trim();
for (CustomersListRootResponseData data : customersListDataFull) {
if (data.getFullname().toLowerCase().contains(filterPattern) || data.getAddress().toLowerCase().contains(filterPattern)) {
filteredList.add(data);
}
}
}
FilterResults filterResults = new FilterResults();
filterResults.values = filteredList;
return filterResults;
}
#Override
protected void publishResults(CharSequence charSequence, FilterResults filterResults) {
customersListData.clear();
customersListData.addAll((List) filterResults.values);
notifyDataSetChanged();
}
};
}
This is the row_assignment.xml which i am inflating in the oncreateViewholder
inside the adapter class this is the layout which wasn't working to load on landscape mode. But i have now created a new resource with landscape and copied the same code from the row_assignment.xml and it worked. I am not sure why it wasn't working because by default android would have picked up the simple row_assignment.xml even if the row_assignment.xml (landscape) wasn't present.
row_assignment.xml
<?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="wrap_content"
android:padding="#dimen/margin_2dp">
<androidx.cardview.widget.CardView
android:id="#+id/container"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_marginStart="8dp"
android:layout_marginTop="8dp"
android:layout_marginEnd="8dp"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.0"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent">
<androidx.constraintlayout.widget.ConstraintLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:id="#+id/tv_customer_name"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_marginStart="8dp"
android:layout_marginTop="16dp"
android:layout_marginEnd="8dp"
android:text="TextView"
android:textStyle="bold"
android:textAppearance="#style/Base.TextAppearance.AppCompat.Medium"
app:layout_constraintEnd_toStartOf="#+id/tv_customer_phone"
app:layout_constraintHorizontal_bias="0.0"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<TextView
android:id="#+id/tv_customer_phone"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_marginTop="16dp"
android:layout_marginEnd="16dp"
android:text="TextView"
android:textAppearance="#style/Base.TextAppearance.AppCompat.Small"
android:textColor="#color/liteBlueColor"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<TextView
android:id="#+id/tv_customer_address"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_marginStart="8dp"
android:layout_marginTop="8dp"
android:layout_marginEnd="8dp"
android:maxLines="1"
android:text="TextView"
android:textAppearance="#style/Base.TextAppearance.AppCompat.Small"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.0"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/tv_customer_name" />
<androidx.constraintlayout.widget.ConstraintLayout
android:id="#+id/constraintLayout3"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_marginBottom="8dp"
app:layout_constraintBottom_toTopOf="#+id/rvCustomersProducts"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/tv_customer_address"
>
<ImageView
android:id="#+id/iv_payments"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="16dp"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.5"
app:layout_constraintStart_toEndOf="#+id/iv_product_edit"
app:layout_constraintTop_toTopOf="parent"
android:background="#drawable/ic_payment_true" />
<ImageView
android:id="#+id/iv_product_edit"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="16dp"
android:layout_marginEnd="16dp"
app:layout_constraintEnd_toStartOf="#+id/iv_payments"
app:layout_constraintHorizontal_bias="0.5"
app:layout_constraintStart_toEndOf="#+id/iv_not_delivered_tick"
app:layout_constraintTop_toTopOf="parent"
android:background="#drawable/ic_edit" />
<ImageView
android:id="#+id/iv_not_delivered_tick"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="16dp"
android:layout_marginEnd="16dp"
app:layout_constraintEnd_toStartOf="#+id/iv_product_edit"
app:layout_constraintHorizontal_bias="0.5"
app:layout_constraintStart_toEndOf="#+id/iv_delivered_tick"
app:layout_constraintTop_toTopOf="parent"
android:background="#drawable/ic_not_deliver"/>
<ImageView
android:id="#+id/iv_delivered_tick"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="16dp"
android:layout_marginEnd="16dp"
android:background="#drawable/ic_deliver"
app:layout_constraintEnd_toStartOf="#+id/iv_not_delivered_tick"
app:layout_constraintHorizontal_bias="0.07"
app:layout_constraintHorizontal_chainStyle="packed"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>
<androidx.recyclerview.widget.RecyclerView
android:id="#+id/rvCustomersProducts"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_marginBottom="8dp"
android:layout_marginTop="8dp"
android:visibility="gone"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toBottomOf="#+id/constraintLayout3"/>
</androidx.constraintlayout.widget.ConstraintLayout>
</androidx.cardview.widget.CardView>
</androidx.constraintlayout.widget.ConstraintLayout>
I am attempting to make a simple app for personal and maybe a few coworkers to use. I am having trouble successfully reading and writing into a Firebase Database.
Some of this code is ripped so there may be mistakes I am looking over without realizing.
I am fairly positive this is something silly and stupid easy to fix, but I just can't see it and have had no success with searching.
The way I am thinking of putting the information into the database is in this fashion.
possible layout?
If there is a better way to lay this out, I'm all ears lol. Hope someone can point me in the right direction. All the files have the proper top lines or 2, and sometimes missing the bottom brace. My computer is being super derpy and deleting some lines for some reason when I am trying to copy/paste.
Rundown of what I am trying to accomplish.
App that will show/store NSNs, name, and description of items
User can enter all of this information themselves to be entered into the database or can search a database for the information. Search part is coming next after I get the easier part down.
information is presented in a CardView form, eventually to be made clickable for more information. information on card will be NSN, name, description, and eventually a picture.
All information is either from user input or directly into the database.
MainActivity.java
import android.app.ProgressDialog;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.provider.MediaStore;
import android.support.annotation.NonNull;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import com.firebase.client.Firebase;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.OnFailureListener;
import com.google.android.gms.tasks.OnSuccessListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.storage.FirebaseStorage;
import com.google.firebase.storage.OnProgressListener;
import com.google.firebase.storage.StorageReference;
import com.google.firebase.storage.UploadTask;
import com.milapps.jd.militemnsnfinder.ShowItemInfo;
import java.io.IOException;
import java.util.UUID;
public class MainActivity extends AppCompatActivity {
//Button Variables
private Button btnChoose, btnUpload, btnSubmit, btnReturn;
private final int PICK_IMAGE_REQUEST = 71;
private Uri filePath;
//Firebase storage
FirebaseStorage storage;
StorageReference storageReference;
// Declaring String variable ( In which we are storing firebase server URL
).
public static final String Firebase_Server_URL = "https://mil-item-nsn-
finder.firebaseio.com/";
// Declaring String variables to store name & phone number get from .
String nsnHolder, nameHolder, descHolder;
//Declaring firebase database
Firebase firebase;
DatabaseReference databaseReference;
// Root Database Name for Firebase Database.
public static final String Database_Path = "Military NSN Database";
//Declaring EditTexts
EditText NameEditText, NSNEditText, DescEditText;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btnSubmit = (Button)findViewById(R.id.btnSubmit_iv);
btnReturn = (Button)findViewById(R.id.btnReturn_iv);
btnChoose = (Button)findViewById(R.id.btnChoose_iv);
btnUpload = (Button)findViewById(R.id.btnUpload_iv);
NameEditText = (EditText)findViewById(R.id.itemNameIV);
NSNEditText = (EditText)findViewById(R.id.itemNSN_iv);
DescEditText = (EditText)findViewById(R.id.itemDesc_iv);
Firebase.setAndroidContext(MainActivity.this);
firebase = new Firebase(Firebase_Server_URL);
databaseReference = FirebaseDatabase.getInstance().getReference(Database_Path);
//Firebase init
storage = FirebaseStorage.getInstance();
storageReference = storage.getReference();
btnChoose.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
chooseImage();
}
});
btnUpload.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
uploadImage();
}
});
btnSubmit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
ItemInfo itemInfo = new ItemInfo();
GetDataFromEditText();
// Adding item name into class function object.
itemInfo.setItemName(nameHolder);
// Adding item NSN into class function object.
itemInfo.setItemNSN(nsnHolder);
//Adding item desc into class function object
itemInfo.setItemDesc(descHolder);
// Getting the ID from firebase database.
String ItemIDFromServer = databaseReference.push().getKey();
// Adding the both name and number values using student details
class object using ID.
databaseReference.child(ItemIDFromServer).setValue(itemInfo);
// Showing Toast message after successfully data submit.
Toast.makeText(MainActivity.this,"Successfully Added",
Toast.LENGTH_LONG).show();
}
});
btnReturn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(MainActivity.this,
ShowItemInfo.class);
startActivity(intent);
}
});
}
private void uploadImage(){
if(filePath != null){
final ProgressDialog progressDialog = new ProgressDialog(this);
progressDialog.setTitle("Uploading...");
progressDialog.show();
StorageReference ref = storageReference.child("images/"+
UUID.randomUUID().toString());
ref.putFile(filePath)
.addOnSuccessListener(new
OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot
taskSnapshot) {
progressDialog.dismiss();
Toast.makeText(MainActivity.this, "Uploaded",
Toast.LENGTH_SHORT).show();
}
})
.addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
progressDialog.dismiss();
Toast.makeText(MainActivity.this, "Failed"
+e.getMessage(), Toast.LENGTH_SHORT).show();
}
})
.addOnProgressListener(new
OnProgressListener<UploadTask.TaskSnapshot>(){
#Override
public void onProgress(UploadTask.TaskSnapshot
taskSnapshot){
double progress = (100.0
*taskSnapshot.getBytesTransferred()/taskSnapshot.getTotalByteCount());
progressDialog.setMessage("Uploaded " +
(int)progress+"%");
}
});
}
}
private void chooseImage(){
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent, "Select
Picture"), PICK_IMAGE_REQUEST);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent
data){
super.onActivityResult(requestCode, resultCode, data);
if(requestCode == PICK_IMAGE_REQUEST && resultCode == RESULT_OK
&& data!= null && data.getData() != null)
{
filePath = data.getData();
try{
Bitmap bitmap =
MediaStore.Images.Media.getBitmap(getContentResolver(), filePath);
}
catch (IOException e){
e.printStackTrace();
}
}
}
public void GetDataFromEditText(){
nameHolder = NameEditText.getText().toString().trim();
descHolder = DescEditText.getText().toString().trim();
nsnHolder = NSNEditText.getText().toString().trim();
}
ItemInfo.java
package com.milapps.jd.militemnsnfinder;
public class ItemInfo {
private String itemName;
private String itemNSN;
private String itemDesc;
public ItemInfo() {
}
public String getItemName() {
return itemName;
}
public void setItemName(String itemName) {
this.itemName = itemName;
}
public String getItemNSN() {
return itemNSN;
}
public void setItemNSN(String itemNSN) {
this.itemNSN = itemNSN;
}
public String getItemDesc() {
return itemDesc;
}
public void setItemDesc(String itemDesc) {
this.itemDesc = itemDesc;
}
}
RecyclerViewAdapter.java
import android.content.Context;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import java.util.List;
public class RecyclerViewAdapter extends
RecyclerView.Adapter<RecyclerViewAdapter.ViewHolder> {
Context context;
List<ItemInfo> MainImageUploadInfoList;
public RecyclerViewAdapter(Context context, List<ItemInfo> TempList) {
this.MainImageUploadInfoList = TempList;
this.context = context;
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view =
LayoutInflater.from(parent.getContext()).inflate(
R.layout.recyclerview_items, parent, false);
ViewHolder viewHolder = new ViewHolder(view);
return viewHolder;
}
#Override
public void onBindViewHolder(ViewHolder holder, int position) {
ItemInfo itemInfo = MainImageUploadInfoList.get(position);
holder.itemName_iv.setText(itemInfo.getItemName());
holder.itemNSN_iv.setText(itemInfo.getItemNSN());
holder.itemDesc_iv.setText(itemInfo.getItemDesc());
}
#Override
public int getItemCount() {
return MainImageUploadInfoList.size();
}
class ViewHolder extends RecyclerView.ViewHolder {
public TextView itemName_iv;
public TextView itemNSN_iv;
public TextView itemDesc_iv;
public ViewHolder(View itemView) {
super(itemView);
itemName_iv = (TextView)
itemView.findViewById(R.id.itemName_iv);
itemDesc_iv = (TextView)
itemView.findViewById(R.id.itemDesc_iv);
itemNSN_iv = (TextView) itemView.findViewById(R.id.itemNSN_iv);
}
}
}
ShowItemInfo.java
package com.milapps.jd.militemnsnfinder;
import android.app.ProgressDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;
import java.util.ArrayList;
import java.util.List;
public class ShowItemInfo extends AppCompatActivity {
DatabaseReference databaseReference;
ProgressDialog progressDialog;
List<ItemInfo> list = new ArrayList<>();
RecyclerView recyclerView;
RecyclerView.Adapter adapter ;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.show_items_list);
recyclerView = (RecyclerView) findViewById(R.id.recyclerView);
recyclerView.setHasFixedSize(true);
recyclerView.setLayoutManager(new
LinearLayoutManager(ShowItemInfo.this));
progressDialog = new ProgressDialog(ShowItemInfo.this);
progressDialog.setMessage("Loading Data from Firebase Database");
progressDialog.show();
databaseReference =
FirebaseDatabase.getInstance().getReference(MainActivity.Database_Path);
databaseReference.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot snapshot) {
for (DataSnapshot dataSnapshot : snapshot.getChildren()) {
ItemInfo itemInfo =
dataSnapshot.getValue(ItemInfo.class);
list.add(itemInfo);
}
adapter = new RecyclerViewAdapter(ShowItemInfo.this, list);
recyclerView.setAdapter(adapter);
progressDialog.dismiss();
}
#Override
public void onCancelled(DatabaseError databaseError) {
progressDialog.dismiss();
}
});
}
}
activity_main.xml
<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="com.milapps.jd.militemnsnfinder.MainActivity"
android:layout_margin="10dp">
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Enter New Item"
android:textSize="20dp"
android:textAlignment="center"
android:textColor="#000"
android:id="#+id/textView" />
<EditText
android:id="#+id/itemNameIV"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_below="#+id/textView"
android:layout_marginTop="15dp"
android:gravity="center"
android:hint="Enter Item Name(Stock)" />
<EditText
android:id="#+id/itemNSN_iv"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_below="#+id/itemNameIV"
android:gravity="center"
android:hint="Enter Item NSN" />
<EditText
android:id="#+id/itemDesc_iv"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_below="#+id/itemNSN_iv"
android:gravity="center"
android:hint="Enter Item Description" />
<Button
android:id="#+id/btnChoose_iv"
android:layout_width="175dp"
android:layout_height="wrap_content"
android:layout_alignBaseline="#+id/btnUpload_iv"
android:layout_alignBottom="#+id/btnUpload_iv"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:text="Choose" />
<Button
android:id="#+id/btnUpload_iv"
android:layout_width="175dp"
android:layout_height="wrap_content"
android:layout_below="#+id/itemDesc_iv"
android:layout_marginTop="53dp"
android:layout_toEndOf="#+id/btnChoose_iv"
android:layout_toRightOf="#+id/btnChoose_iv"
android:text="Upload" />
<Button
android:id="#+id/btnSubmit_iv"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_below="#+id/btnChoose_iv"
android:layout_marginTop="32dp"
android:text="Submit" />
<Button
android:id="#+id/btnReturn_iv"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_below="#+id/btnSubmit_iv"
android:layout_marginTop="18dp"
android:text="Return" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_above="#+id/btnChoose_iv"
android:layout_centerHorizontal="true"
android:ems="10"
android:gravity="center"
android:inputType="textPersonName"
android:text="Upload Picture(Optional)" />
</RelativeLayout>
content_show_student_details.xml
<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"
app:layout_behavior="#string/appbar_scrolling_view_behavior"
tools:context="com.milapps.jd.militemnsnfinder.ShowItemInfo"
tools:showIn="#layout/show_items_list">
</android.support.constraint.ConstraintLayout>
recyclerview_items.xml
<android.support.v7.widget.CardView
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:card_view="http://schemas.android.com/apk/res-auto"
android:id="#+id/cardview1"
android:layout_width="match_parent"
android:layout_height="75dp"
android:layout_margin="8dp"
>
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_margin="1dp"
android:orientation="vertical">
<TextView
android:id="#+id/itemName_iv"
android:layout_width="233dp"
android:layout_height="25dp"
android:text="something" />
<TextView
android:id="#+id/itemNSN_iv"
android:layout_width="233dp"
android:layout_height="25dp"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_centerVertical="true"
android:text="something" />
<TextView
android:id="#+id/itemDesc_iv"
android:layout_width="232dp"
android:layout_height="25dp"
android:layout_alignEnd="#+id/itemName_iv"
android:layout_alignParentBottom="true"
android:layout_alignRight="#+id/itemName_iv"
android:text="something" />
<ImageView
android:id="#+id/imageView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentEnd="true"
android:layout_alignParentRight="true"
android:layout_centerVertical="true"
card_view:srcCompat="#mipmap/ic_launcher" />
</RelativeLayout>
</android.support.v7.widget.CardView>
show_items_list.xml
<android.support.constraint.ConstraintLayout
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.milapps.jd.militemnsnfinder.ShowItemInfo">
<android.support.v7.widget.RecyclerView
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:id="#+id/recyclerView"
android:layout_alignParentTop="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true">
</android.support.v7.widget.RecyclerView>
</android.support.constraint.ConstraintLayout>
First, in your POJO make sure the name of the constants are equal to the ones in your firebase database, first in your firebase database you have item Name and in your pojo itemName , you should put in your firebase either item_Name or itemName , if you put item_Name refactor the name in your pojo but keep the same names in the pojo and the firebase
Second, your reference must be like this .child("items").child("item_NSN").... , or .child("items/item_NSN")..... but please do not use blank spaces in names inside firebase
Last, please update your firebase rules if they are not able to write and read for everyone without sign in first
go to your realtime database and find rules, inside you should have this
// These rules require authentication
{
"rules": {
".read": "auth != null",
".write": "auth != null"
}
}
if you want to each one read and write data without authentication just change that rules to this
// These rules do not require authentication
// These rules give anyone, even people who are not users of your app,
// read and write access to your database
{
"rules": {
".read": true,
".write": true
}
}
So my brain is no longer fried. So when trying to enter information via the submit button, I "think" I fixed my reference but I'm not 100%. Still a little confused from it.
btnSubmit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String itemNSN;
ItemInfo itemInfo = new ItemInfo();
GetDataFromEditText();
// Adding item name into class function object.
itemInfo.setItemName(nameHolder);
// Adding item NSN into class function object.
itemInfo.setItemNSN(nsnHolder);
itemNSN = nsnHolder;
//Adding item desc into class function object
itemInfo.setItemDesc(descHolder);
// Getting the ID from firebase database.
String ItemIDFromServer = databaseReference.push().getKey();
// Adding the both name and number values using student details
class object using ID.
databaseReference.child("items").setValue(itemNSN);
databaseReference.child("items/itemNSN").setValue(itemInfo);
// Showing Toast message after successfully data submit.
Toast.makeText(MainActivity.this,"Successfully Added",
Toast.LENGTH_LONG).show();
}
});
Then to pull all the information via the return button, I am unsure of what is supposed to be but I haven't changed it at all. I have the cardview layout I would like for it. but this is my btnReturn clickListener.
btnReturn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(MainActivity.this,
ShowItemInfo.class);
startActivity(intent);
}
});
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