So, I have scoured the interwebs and I cannot find a solution for this based on other people's experiences, so I am posting this issue. (Please note that this is my 1st android app experience and I am debugging / updating an existing app.)
When I implement my custom NotesListAdapter (extends BaseAdapter) on the ListView, mListNotesView (mListNotesView.setAdapter(this)), and load the data into the ArrayList mNoteList, the getView function is not being called. Also, I found that mListNotesView.setBackgroundResource is not chaning the background of the control, either. I have a similar implementation on a previous activity that works exactly correct. When I copied over the class and changed it to handle my ArrayList, it broke. I have getCount returning the ArrayList size(), which is not 0, and getItemId returns position. I have a feeling it may be my XML or my setup because it's acting like the ListView is not visible. I am perplexed. How do I get the ListView to show? Anything inside of the getView has not been reached so it may be buggy.
ViewTicketOrderActivity (Some parts ommitted for size)
public class ViewTicketOrderActivity extends Activity {
MySQLDatabase myDataBase;
Ticket mTicket;
public ArrayList<Notes> mNotes = new ArrayList<Notes>();
String mErrorString;
Button mAddUpdateButton;
Button mAcceptButton;
//Button mViewNotesButton;
NotesListAdapter mNotesListAdapter;
static final int ERROR_DIALOG = 0;
static final int SUCCESS_DIALOG = 1;
static final int COMPLETED_DIALOG = 2;
static final int RESTART_DIALOG = 3;
static final int LOADING = 0;
static final int LOAD_ERROR = 1;
static final int LOADED = 4;
static final String TICKET_EXTRA = "ticket_extra";
static final String TAG = "ViewTicketOrderActivity";
private static final boolean gDebugLog = false;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.viewticketorder);
Activity context = this;
String theTitle = "Sundance Ticket Order";
theTitle += (MySQLDatabase.TESTING == true) ? " (DEV SERVER)" : " (LIVE)";
setTitle(theTitle);
myDataBase = MySQLDatabase.getMySQLDatabase(this);
if (gDebugLog) {
DebugLogger.logString(TAG, ".onCreate");
}
mNotesListAdapter = new NotesListAdapter(context, R.id.note_list);
Log.d(this.toString(),this.mNotesListAdapter.toString());
}
private class NotesListAdapter extends BaseAdapter {
private LayoutInflater mInflater;
private ArrayList<Notes> mNoteList;
private ListView mListNotesView;
private Activity mActivity;
int mState = LOADING;
String mErrorMessage;
private NotesListAdapter(Activity context, int listViewID) {
mActivity = context;
mNoteList = new ArrayList<Notes>();
mInflater = LayoutInflater.from(context);
mListNotesView = (ListView)context.findViewById(listViewID);
mListNotesView.setBackgroundResource(R.color.emergency_red);
mListNotesView.setAdapter(this);
Log.d(mListNotesView.toString(), String.valueOf(mListNotesView.getCount()));
this.notifyDataSetChanged();
//mListNotesView.setVisibility(View.VISIBLE);
}
void setLoading()
{
mState = LOADING;
this.notifyDataSetChanged();
}
void setLoadError(String errorString)
{
mState = LOAD_ERROR;
mErrorMessage = errorString;
this.notifyDataSetChanged();
}
void setNoteList(ArrayList<Notes> inNotes)
{
mState = LOADED;
mNoteList.clear();
mNoteList.addAll(inNotes);
Log.d("SetNoteList", "TRUE " + inNotes);
//mNoteList = mNotes;
this.notifyDataSetChanged();
}
/**
* Use the array index as a unique id.
*
* #see android.widget.ListAdapter#getItemId(int)
*/
#Override
public long getItemId(int position) {
return position;
}
public int getCount(){
if (mState == LOADED) {
Log.d("getCount",String.valueOf(mNoteList.size()));
return mNoteList.size();
} else {
return 0;
}
}
/**
* Make a view to hold each row.
*
* #see android.widget.ListAdapter#getView(int, android.view.View,
* android.view.ViewGroup)
*/
#Override
public View getView(int position, View convertView, ViewGroup parent) {
// A ViewHolder keeps references to children views to avoid unneccessary calls
// to findViewById() on each row.
Log.d("getView",this.toString());
if (mState == LOADED) {
ViewHolder holder;
// When convertView is not null, we can reuse it directly, there
// is no need
// to reinflate it. We only inflate a new View when the
// convertView supplied
// by ListView is null.
Notes note = this.getItem(position);
if (convertView == null) {
/*if (ticket.emergency())
{
convertView = mInflater.inflate(R.layout.emergency_ticket_list_item_opt,
null);
}
else
{
convertView = mInflater.inflate(R.layout.ticket_list_item,
null);
}*/
convertView = mInflater.inflate(R.layout.noteslist_item,
null);
// Creates a ViewHolder and store references to the two
// children views
// we want to bind data to.
holder = new ViewHolder();
holder.noteText = (TextView) convertView
.findViewById(R.id.text_note);
holder.dateText = (TextView) convertView
.findViewById(R.id.text_note_date);
holder.createByText = (TextView) convertView
.findViewById(R.id.text_note_by);
holder.createByIDText = (TextView) convertView
.findViewById(R.id.text_note_by_id);
convertView.setTag(holder);
} else {
// Get the ViewHolder back to get fast access to the
// TextView
// and the ImageView.
holder = (ViewHolder) convertView.getTag();
}
// Bind the data efficiently with the holder.
holder.noteText.setText(note.note());
holder.dateText.setText(note.date());
holder.createByText.setText(note.createBy());
holder.createByIDText.setText(note.employeeID());
if(!mTicket.employeeID().equals(note.employeeID())){
convertView.setBackgroundResource(R.drawable.solid_purple);
}
} else if (mState == LOADING ) {
if (convertView == null) {
convertView = mInflater.inflate(R.layout.loading_view,
null);
}
TextView messageText = (TextView)convertView.findViewById(R.id.message);
messageText.setText("Loading tickets");
} else if (mState == LOAD_ERROR) {
if (convertView == null) {
convertView = mInflater.inflate(R.layout.load_error_view,
null);
}
TextView messageText = (TextView)convertView.findViewById(R.id.message);
messageText.setText("Error loading tickets");
String errorString = mErrorMessage != null ? mErrorMessage : "";
TextView errorText = (TextView)convertView.findViewById(R.id.errorText);
errorText.setText(errorString);
}
return convertView;
}
class ViewHolder {
TextView noteText;
TextView dateText;
TextView createByText;
TextView createByIDText;
}
//#Override
/*public int getCount() {
*//*if (mState == LOADED) {
*//*
Log.d("getCount mState " + mState,String.valueOf(mNoteList.size())+", "+String.valueOf(mNotes.size()));
return mNoteList.size();
*//*} else {
Log.d("getCount mState " + mState,"0");
return 0;
}*//*
}*/
#Override
public Notes getItem(int position) {
Log.d("getItem",mNoteList.get(position).toString());
return mNoteList.get(position);
}
#Override
public int getItemViewType (int position) {
int result = mState;
Log.d("getItemId",String.valueOf(position));
return result;
}
#Override
public int getViewTypeCount ()
{
return 4;
}
}
protected void onResume() {
super.onResume();
Bundle extras = getIntent().getExtras();
if(extras !=null)
{
mTicket = (Ticket)extras.getSerializable(TICKET_EXTRA);
}
else
{
mTicket = new Ticket();
}
if (mTicket.emergency())
{
setContentView(R.layout.view_emergency_ticketorder);
}
else
{
setContentView(R.layout.viewticketorder);
}
if (gDebugLog)
{
DebugLogger.logString(TAG, ".onResume mTicket " + mTicket);
}
TicketCheckService.clearNotificationForNewTicket(mTicket);
new GetTicketTask().execute();
new GetNotesTask().execute();
updateDisplayedTicket();
}
private void updateDisplayedTicket() {
mAddUpdateButton = (Button)findViewById(R.id.addUpdateButton);
mAcceptButton = (Button)findViewById(R.id.acceptButton);
//mViewNotesButton = (Button)findViewById(R.id.viewNotesButton);
String ticketStatus = myDataBase.getDescriptionStringForStatusString(mTicket.status());
if(ticketStatus == "Job Rejected") {
mAddUpdateButton.setText("Restart Job");
} else {
mAddUpdateButton.setText("Add Update");
}
if(ticketStatus == "Requested") {
mAcceptButton.setText("Accept");
} else if(ticketStatus != "Requested") {
mAcceptButton.setText("Back");
}
//mViewNotesButton.setText(R.string.viewNotes);
TextView idText = (TextView)findViewById(R.id.textTicketID);
idText.setText(mTicket.id());
//TextView descriptionText = (TextView)findViewById(R.id.textDescription);
//descriptionText.setText(mTicket.description());
TextView titleText = (TextView)findViewById(R.id.textTitle);
titleText.setText(mTicket.title());
TextView storeIDText = (TextView)findViewById(R.id.textStoreID);
storeIDText.setText(mTicket.store());
String formatPhone;
TextView storePhoneText = (TextView)findViewById(R.id.textStorePhone);
if(mTicket.phoneNo().isEmpty()){
formatPhone = "NO PHONE NO.";
} else {
storePhoneText = (TextView) findViewById(R.id.textStorePhone);
formatPhone = mTicket.phoneNo().replaceFirst("(\\d{3})(\\d{3})(\\d+)", "($1)$2-$3");
storePhoneText.setOnClickListener(new CallClickListener(mTicket.phoneNo()));
}
storePhoneText.setText(formatPhone);
TextView categoryText = (TextView)findViewById(R.id.textCategory);
String categoryDescription = MySQLDatabase.getDescriptionStringForCategoryString(mTicket.category());
categoryText.setText(categoryDescription);
if(ticketStatus == "Completed Pending") {
showDialog(COMPLETED_DIALOG);
}
}
public void onClickAccept(View v) {
try {
boolean maint = myDataBase.getSystemMaintStatus();
if(maint) {
setLoadError("The phone app is down for maintenance.");
return;
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
if(mAcceptButton.getText() =="Accept") {
mAddUpdateButton.setEnabled(false);
mAcceptButton.setEnabled(false);
new AcceptTicketTask().execute();
} else {
finish();
}
}
public void onClickAddUpdate(View v) {
try {
boolean maint = myDataBase.getSystemMaintStatus();
if(maint) {
setLoadError("The phone app is down for maintenance.");
return;
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
if(mAddUpdateButton.getText() =="Add Update") {
Intent i = new Intent(this, UpdateTicketActivity.class);
i.putExtra(UpdateTicketActivity.TICKET_EXTRA, mTicket);
startActivity(i);
} else if(mAddUpdateButton.getText() =="Restart Job") {
mAddUpdateButton.setEnabled(false);
mAcceptButton.setEnabled(false);
new RestartTicketTask().execute();
}
}
private class AcceptTicketTask extends AsyncTask<Void, Integer, String>
{
protected String doInBackground(Void... parent) {
mErrorString = null;
String result = null;
String updateTime = DateFormat.getDateTimeInstance().format(new Date(0));
try {
boolean success = myDataBase.updateTicket(mTicket.id(), mTicket.employeeID(), mTicket.description(), "1", updateTime, null);
if (!success)
{
result = "Could not update Ticket";
}
} catch (IOException e) {
// TODO Auto-generated catch block
result = "Could not update Ticket - " + e.getLocalizedMessage();
e.printStackTrace();
}
return result;
}
protected void onProgressUpdate(Integer... progress) {
}
protected void onPostExecute(String errorString) {
if (null != errorString) {
mErrorString = errorString;
showDialog(ERROR_DIALOG);
} else {
showDialog(SUCCESS_DIALOG);
mAcceptButton.setText("Back");
}
mAddUpdateButton.setEnabled(true);
mAcceptButton.setEnabled(true);
}
}
private class RestartTicketTask extends AsyncTask<Void, Integer, String>
{
protected String doInBackground(Void... parent) {
mErrorString = null;
String result = null;
String updateTime = DateFormat.getDateTimeInstance().format(new Date(0));
try {
boolean success = myDataBase.updateTicket(mTicket.id(), mTicket.employeeID(), mTicket.description(), "7", updateTime, null);
if (!success)
{
result = "Could not update Ticket";
}
} catch (IOException e) {
// TODO Auto-generated catch block
result = "Could not update Ticket - " + e.getLocalizedMessage();
e.printStackTrace();
}
return result;
}
protected void onProgressUpdate(Integer... progress) {
}
protected void onPostExecute(String errorString)
{
if (null != errorString) {
mErrorString = errorString;
showDialog(ERROR_DIALOG);
} else {
showDialog(RESTART_DIALOG);
mAcceptButton.setText("Done");
mAddUpdateButton.setText("Add Update");
}
mAddUpdateButton.setEnabled(true);
mAcceptButton.setEnabled(true);
}
}
private class GetTicketTask extends AsyncTask<Void, Integer, Ticket>
{
String mError = null;
protected Ticket doInBackground(Void... parent) {
Ticket result = null;
try {
result = myDataBase.getTicketWithID(mTicket.id(), mTicket.employeeID());
} catch (IOException e) {
// TODO Auto-generated catch block
mError = e.getLocalizedMessage();
e.printStackTrace();
}
return result;
}
protected void onProgressUpdate(Integer... progress) {
}
protected void onPostExecute(Ticket result)
{
if (null != result) {
mTicket = result;
} else {
setLoadError(mError);
}
}
}
private class GetNotesTask extends AsyncTask<Void, Integer, ArrayList<Notes>> {
String mError = null;
protected ArrayList<Notes> doInBackground(Void... parent) {
ArrayList<Notes> result = new ArrayList<Notes>();
try {
result = myDataBase.getTicketNotes(mTicket.id());
} catch (IOException e) {
// TODO Auto-generated catch block
myDataBase.debugLog("Error caught" + e);
mError = e.getLocalizedMessage();
e.printStackTrace();
}
return result;
}
protected void onProgressUpdate(Integer... progress) {
}
protected void onPostExecute(ArrayList<Notes> result) {
if (null != result) {
Log.d("Result", result.toString());
mNotes = result;
} else {
Log.d("SetNoteList","FALSE");
mNotesListAdapter.setLoadError(mError);
}
}
}
private void updateDisplayedNotes(){
ArrayList<Notes> newNotes = mNotes;
if(newNotes != null) {
mNotesListAdapter.setNoteList(newNotes);
}
}
/*private class updateDisplayedNotes extends AsyncTask<Void, Integer, ArrayList<Notes>> {
public ArrayList<Notes> newNotes = new ArrayList<Notes>();
public updateDisplayedNotes(){
super();
Log.d(this.toString(), "Updating");
}
protected ArrayList<Notes> doInBackground(Void... parent) {
Log.d(this.toString(), "Background Task");
for (Notes note : mNotes) {
Log.d(this.toString(),note.toString());
if(note != null) {
Log.d(this.toString(), "Note Added");
newNotes.add(note);
}
}
return newNotes;
}
protected void onPostExecute(ArrayList<Notes> newNotes)
{
if(newNotes != null) {
mNotes.clear();
mNotes.addAll(newNotes);
mNotesListAdapter.setNoteList(mNotes);
}
}
}*/
void setLoadError(String error) {
setContentView(R.layout.load_error_view);
TextView messageText = (TextView)findViewById(R.id.message);
messageText.setText("Error loading ticket");
String errorString = error != null ? error : "";
TextView errorText = (TextView)findViewById(R.id.errorText);
errorText.setText(errorString);
finish();
}
}
viewticketorder.xml (where note_list is)
<?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:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#drawable/background"
android:orientation="vertical"
tools:context=".ViewTicketOrderActivity"
tools:ignore="HardcodedText" >
<TextView
android:id="#+id/textTitle"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginLeft="10dp"
android:layout_marginRight="10dp"
android:layout_marginTop="3dp"
android:paddingLeft="3dp"
android:paddingRight="3dp"
android:text="#string/loadingTicket"
android:textAppearance="?android:attr/textAppearanceLarge"
android:textColor="#color/white_color"
android:textSize="20dp"
android:textIsSelectable="true"
android:background="#drawable/title_transparent_bg"/>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal" >
<TextView
android:id="#+id/TextView01"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="3dp"
android:paddingTop="2dp"
android:paddingLeft="10dp"
android:text="#string/ticketID"
android:textAppearance="?android:attr/textAppearanceSmall"
tools:ignore="HardcodedText" />
<TextView
android:id="#+id/textTicketID"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="10dp"
android:layout_marginRight="10dp"
android:layout_marginTop="3dp"
android:textAppearance="?android:attr/textAppearanceSmall"
android:focusable="true"
android:textColor="#color/white_color"
android:textIsSelectable="true"/>
<TextView
android:id="#+id/textView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="10dp"
android:layout_marginTop="3dp"
android:paddingTop="2dp"
android:text="#string/storeID"
android:textAppearance="?android:attr/textAppearanceSmall"
tools:ignore="HardcodedText" />
<TextView
android:id="#+id/textStoreID"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="10dp"
android:layout_marginRight="10dp"
android:layout_marginTop="3dp"
android:textAppearance="?android:attr/textAppearanceSmall"
android:focusable="true"
android:textColor="#color/white_color"
android:textIsSelectable="true"/>
<TextView
android:id="#+id/textStorePhone"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="10dp"
android:layout_marginRight="10dp"
android:layout_marginTop="3dp"
android:textAppearance="?android:attr/textAppearanceSmall"
android:focusable="true"
android:textColor="#color/white_color"
android:textIsSelectable="true"
/>
</LinearLayout>
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="horizontal" >
<TextView
android:id="#+id/TextView05"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="10dp"
android:paddingTop="2dp"
android:text="#string/category"
android:textAppearance="?android:attr/textAppearanceSmall" />
<TextView
android:id="#+id/textCategory"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="10dp"
android:layout_marginRight="10dp"
android:gravity="center_vertical"
android:text=""
android:textAppearance="?android:attr/textAppearanceSmall"
android:textColor="#color/white_color"
android:focusable="true"
android:textIsSelectable="true"/>
</LinearLayout>
<ListView
android:id="#+id/note_list"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="5"
android:divider="#drawable/ticket_item_divider"
android:dividerHeight="1dp"
tools:ignore="NestedWeights"
android:choiceMode="singleChoice"
android:clickable="true"
android:background="#drawable/title_transparent_bg">
</ListView>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content" >
<Button
android:id="#+id/acceptButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="10dp"
android:layout_marginRight="2dp"
android:layout_weight="1"
android:onClick="onClickAccept" />
<Button
android:id="#+id/addUpdateButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="2dp"
android:layout_marginRight="10dp"
android:layout_weight="1"
android:onClick="onClickAddUpdate" />
</LinearLayout>
</LinearLayout>
notelist_item.xml (inflator)
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/text_note_item"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#80FFFFFF"
android:orientation="vertical"
>
<TextView
android:id="#+id/text_note"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:paddingLeft="10dp"
android:paddingRight="10dp"
android:text="#string/filler_string"
android:textAppearance="?android:attr/textAppearanceMedium"
android:textColor="#color/text_item_color"
android:textSize="#dimen/big_text_item_size" />
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:layout_weight=".70"
>
<TextView
android:id="#+id/text_note_date"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:paddingLeft="10dp"
android:paddingRight="10dp"
android:text="#string/filler_string"
android:textAppearance="?android:attr/textAppearanceSmall"
android:textColor="#color/text_sub_item_color" />
<TextView
android:id="#+id/text_note_by"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:paddingLeft="10dp"
android:paddingRight="10dp"
android:text="#string/filler_string"
android:textAppearance="?android:attr/textAppearanceSmall"
android:textColor="#color/text_sub_item_color" />
<TextView
android:id="#+id/text_note_by_id"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:paddingLeft="10dp"
android:paddingRight="10dp"
android:text="#string/filler_string"
android:textAppearance="?android:attr/textAppearanceSmall"
android:textColor="#color/text_sub_item_color" />
</LinearLayout>
</LinearLayout>
I'm going to recommend you reorganize your code. Here are some general tips:
1) Keep your views like ListView in the Activity class. Don't try to inflate the view in your adapter class. So in your activity's onCreate() after setContentView() you should have something like:
ListView listView = (ListView) findViewById(R.id.listView);
2) Next you need to get the data that will be shown in the listview and store it in a list. I didn't see in your code where the data comes from, but let's just say it comes from a database. You should create something like an ArrayList and store the data that you want to show in the ListView in the ArrayList
3) Next you need to create an adapter and pass the list of data into the adapter.
4) Once this has been done the ListView now has an adapter that will supply data to it. If you've done everything correctly then the system will eventually call getView() automatically and your code inside that should run and render the view.
Not an exact solution, but hopefully this explanation will help you figure it out.
Related
I'm trying take screenshot of a cardview which is in a DialogFragment. When I take a screenshot via Code. Top rounded corners are not showing but the bottom rounded corners are showing correctly. I saw these issues mentioned in the below Questions...
Cardview loses its radius when taken a screenshot programmatically
Using PixelCopy to copy a scaled View within a DialogFragment
As per the above question, I tested the same layout & code in a Fragment class. Then the rounded corners are showing up correctly...
LAYOUT
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 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:id="#+id/mainlinear"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:padding="12dp"
android:layout_margin="18dp">
<androidx.cardview.widget.CardView
android:id="#+id/cardView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
app:cardCornerRadius="28dp">
<RelativeLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="#color/colorCand"
android:orientation="vertical">
<androidx.appcompat.widget.AppCompatImageView
android:id="#+id/image"
android:layout_width="match_parent"
android:layout_height="320dp"
android:background="#color/colorWhite"
android:scaleType="centerCrop"
android:src="#drawable/turtle" />
<LinearLayout
android:id="#+id/header"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="#+id/image"
android:background="#color/colorAccent">
<androidx.appcompat.widget.AppCompatImageView
android:id="#+id/type"
android:layout_width="48dp"
android:layout_height="48dp"
android:layout_gravity="center"
android:layout_marginStart="8dp"
android:src="#drawable/ic_idea" />
<TextView
android:id="#+id/title"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="center_vertical"
android:layout_marginEnd="8dp"
android:maxLines="1"
android:textAlignment="textEnd"
android:textAllCaps="true"
android:textColor="#color/colorWhite"
android:textSize="18sp"
android:textStyle="bold"
tools:ignore="RtlCompat"
tools:text="Sea Turtle Day" />
</LinearLayout>
<RelativeLayout
android:id="#+id/desc"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="#+id/header"
android:background="#color/colorGray">
<TextView
android:id="#+id/tag"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:layout_marginStart="12dp"
android:layout_marginEnd="8dp"
android:layout_toStartOf="#id/category_icon"
android:maxLines="2"
android:textColor="#color/colorAccent"
tools:text="#SeaTurtleDay#SeaTurtleDay" />
<androidx.appcompat.widget.AppCompatImageView
android:id="#+id/category_icon"
android:layout_width="48dp"
android:layout_height="48dp"
android:layout_alignParentEnd="true"
android:layout_centerVertical="true"
android:layout_marginStart="4dp"
android:layout_marginEnd="4dp"
android:src="#drawable/animals" />
</RelativeLayout>
<androidx.appcompat.widget.AppCompatImageView
android:id="#+id/logo"
android:layout_width="96dp"
android:layout_height="96dp"
android:layout_below="#+id/desc"
android:layout_centerHorizontal="true"
android:layout_gravity="center"
android:layout_margin="8dp"
android:src="#drawable/wwf_logo" />
</RelativeLayout>
</androidx.cardview.widget.CardView>
</LinearLayout>
ShotDialog.java
public class ShotDialog extends DialogFragment {
StkyrDialogBinding mBind;
private static Context mCon;
private static Boolean viaEntity;
private String mLink;
public ShotDialog() {
}
public static ShotDialognewInstance(Context context, Stkyr mStk, Boolean entityOnclick) {
StkyrDialog frag = new StkyrDialog();
mCon = context;
viaEntity = entityOnclick;
Bundle args = new Bundle();
args.putSerializable("STK", mStk);
frag.setArguments(args);
return frag;
}
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
mBind = ShotDialogBinding.inflate(inflater);
getDialog().getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
mBind.fwd.setOnClickListener(view -> {
FragmentManager fm = ((FragmentActivity) mCon).getSupportFragmentManager();
BottomDialogFragment mBot = BottomDialogFragment.newInstance(mCon, mBind.mainlinear);
mBot.show(fm, "ShareDialog");
});
}
return mBind.getRoot();
}
}
BottomDialogFragment.java (From this Bottomsheet the screenshot code is triggered for the above Dialog)
public class BottomDialogFragment extends BottomSheetDialogFragment {
public static Context mCon;
private static View stkView;
DialogShareBinding mBind;
private String sharePath = "no";
public static BottomDialogFragment newInstance(Context context, View view) {
mCon = context;
stkView = view;
return new BottomDialogFragment();
}
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
mBind = DialogShareBinding.inflate(inflater);
return mBind.getRoot();
}
#Override
public void onViewCreated(#NonNull View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
mBind.stkShare.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
dismiss();
}
});
mBind.share.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
dismiss();
Log.e("onClick: ", "SS TRIGGER");
takeStkShot();
}
});
}
public void takeStkShot() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
ViewImage.Companion.getScreenShotFromView(stkView, getActivity(), (bm) -> {
Log.e("takeStkShot: ", "> > >");
storeImage(bm);
return null;
});
} else {
Bitmap bm = ViewImage.Companion.getScreenShot(stkView);
storeImage(bm);
Log.e("takeStkShot: ", "> > > ScreenShot");
}
}
private void storeImage(Bitmap bm) {
Log.e("takeScreenshot: ", "STORING");
Date now = new Date();
android.text.format.DateFormat.format("yyyy-MM-dd hh:mm", now);
try {
// image naming and path to include sd card appending name you choose for file
String mPath = Environment.getExternalStorageDirectory().toString() + "/" + now + ".jpeg";
try {
Log.d("ShareImageCreate", bm.toString());
File imageFile = new File(mPath);
FileOutputStream outputStream = new FileOutputStream(imageFile);
int quality = 100;
bm.compress(Bitmap.CompressFormat.JPEG, quality, outputStream);
outputStream.flush();
outputStream.close();
//setting screenshot in imageview
String filePath = imageFile.getPath();
Log.e("takeScreenshot > > ", filePath);
Bitmap ssbitmap = BitmapFactory.decodeFile(imageFile.getAbsolutePath());
//iv.setImageBitmap(ssbitmap);
sharePath = filePath;
Log.d("ShareImageCreate", sharePath);
Toast.makeText(getActivity(),"SCREENSHOT STORED!",Toast.LENGTH_SHORT).show();
} catch (NullPointerException ex) {
ex.printStackTrace();
}
} catch (Throwable e) {
// Several error may come out with file handling or DOM
e.printStackTrace();
}
}
}
ShotFragment.java (This Gives expected result with rounded corners)
public class ShotFragment extends Fragment {
String mEntityType = Constants.CAUSE;
Bundle mBundle;
ExtendedFloatingActionButton nextFab;
AppCompatImageView img;
CardView mCard;
private String sharePath = "no";
public View onCreateView(#NonNull LayoutInflater inflater,
ViewGroup container, Bundle savedInstanceState) {
View root = inflater.inflate(R.layout.dialog_test, container, false);
((AppCompatActivity) getActivity()).getSupportActionBar().setDisplayHomeAsUpEnabled(true);
((AppCompatActivity) getActivity()).getSupportActionBar().setDisplayShowHomeEnabled(true);
((AppCompatActivity) getActivity()).getSupportActionBar().setTitle("Create Screenshot");
mCard = root.findViewById(R.id.cardView);
mCard.setOnClickListener(view -> {
takeStkShot();
return root;
}
public void takeStkShot() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
ViewImage.Companion.getScreenShotFromView(mCard, getActivity(), (bm) -> {
Log.e("takeStkShot: ", "> > >");
storeImage(bm);
return null;
});
} else {
Bitmap bm = ViewImage.Companion.getScreenShot(mCard);
storeImage(bm);
Log.e("takeStkShot: ", "> > > ScreenShot");
}
}
private void storeImage(Bitmap bm) {
Log.e("takeScreenshot: ", "STORING");
Date now = new Date();
android.text.format.DateFormat.format("yyyy-MM-dd hh:mm", now);
try {
// image naming and path to include sd card appending name you choose for file
String mPath = Environment.getExternalStorageDirectory().toString() + "/" + now + ".jpeg";
// create bitmap screen capture
//View v1 = lyTakeScreenShots.getRootView();
try {
Log.d("ShareImageCreate", bm.toString());
File imageFile = new File(mPath);
FileOutputStream outputStream = new FileOutputStream(imageFile);
int quality = 100;
bm.compress(Bitmap.CompressFormat.JPEG, quality, outputStream);
outputStream.flush();
outputStream.close();
//setting screenshot in imageview
String filePath = imageFile.getPath();
Log.e("takeScreenshot > > ", filePath);
Bitmap ssbitmap = BitmapFactory.decodeFile(imageFile.getAbsolutePath());
//iv.setImageBitmap(ssbitmap);
sharePath = filePath;
Log.d("ShareImageCreate", sharePath);
Toast.makeText(getActivity(),"SCREENSHOT STORED!",Toast.LENGTH_SHORT).show();
} catch (NullPointerException ex) {
ex.printStackTrace();
}
} catch (Throwable e) {
// Several error may come out with file handling or DOM
e.printStackTrace();
}
}
Try the following as a replacement for ViewImage.kt in the referenced project. The main change is to pass in the view's window rather than an Activity. Dialogs have their own windows and don't share a window with activities.
ViewImage.kt
/**
* Bulk of code borrowed from "Taking Screenshot Programmatically Using PixelCopy Api"
* by Shivesh Karan Mehta
* https://medium.com/#shiveshmehta09/taking-screenshot-programmatically-using-pixelcopy-api-83c84643b02a
*/
class ViewImage {
companion object {
#JvmStatic
fun getScreenShotFromView(view: View, window: Window, callback: (Bitmap) -> Unit) {
val bitmap: Bitmap
// PixelCopy is available since API 24 but doesn't seem to work 100% until API 29.
// The build version statement can be adjusted according to how well PixelCopy
// works in your environment before "P".
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) {
val locationOfView = IntArray(2)
view.getLocationInWindow(locationOfView)
val rect = Rect(locationOfView[0], locationOfView[1],
locationOfView[0] + view.width, locationOfView[1] + view.height)
bitmap = Bitmap.createBitmap(view.width, view.height, Bitmap.Config.ARGB_8888)
try {
PixelCopy.request(window, rect, bitmap,
{ copyResult: Int ->
if (copyResult == PixelCopy.SUCCESS) {
callback(bitmap)
}
// possible to handle other result codes ...
},
Handler()
)
} catch (e: IllegalArgumentException) {
// PixelCopy may throw IllegalArgumentException, make sure to handle it
e.printStackTrace()
}
} else {
bitmap = getScreenShot(view)
callback(bitmap)
}
}
// Method which will return Bitmap after taking screenshot. We have to pass the view which
// we want to take screenshot.
#Suppress("DEPRECATION")
#JvmStatic
fun getScreenShot(view: View): Bitmap {
view.isDrawingCacheEnabled = true
val bitmap = Bitmap.createBitmap(view.drawingCache)
view.isDrawingCacheEnabled = false
return bitmap
}
}
}
I Noticed that you are trying to take a screenshot from 'mainRelative' which does not exist in your xml, I think you should use the id of 'cardView' or 'mainlinear' based on your requirements.
The Answer given by #Cheticamp is right
Lets Convert it into java
public class ScreenshotTaker {
private static final String TAG = ScreenshotTaker.class.getSimpleName();
/**
* Takes screenshot of given view and saves it in external storage
* #param view outer most ViewGroup that you want a screenshot of
* #return File object of saved screenshot in storage
*/
public static File captureScreenshot(View view) {
Bitmap bitmap = Bitmap.createBitmap(view.getWidth(),
view.getHeight(), Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(bitmap);
view.draw(canvas);
return saveBitmap(view.getContext(),bitmap);
}
public interface screenshotFile{
void onComplete(File file);
}
public static void getScreenShotFromView(View view, Window window, screenshotFile callback ) {
Bitmap bitmap;
// PixelCopy is available since API 24 but doesn't seem to work 100% until API 29.
// The build version statement can be adjusted according to how well PixelCopy
// works in your environment before "P".
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) {
int[] locationOfView = new int[2];
view.getLocationInWindow(locationOfView);
Rect rect = new Rect(locationOfView[0], locationOfView[1],
locationOfView[0] + view.getWidth(), locationOfView[1] + view.getHeight());
bitmap = Bitmap.createBitmap(view.getWidth(), view.getHeight(), Bitmap.Config.ARGB_8888);
try {
PixelCopy.request(window, rect, bitmap, new PixelCopy.OnPixelCopyFinishedListener() {
#Override
public void onPixelCopyFinished(int copyResult) {
if (copyResult == PixelCopy.SUCCESS) {
callback.onComplete(saveBitmap(view.getContext(),bitmap));
}
}
}, new Handler()
);
}catch (Exception ignored){ }
}
}
}
Six RadioButtons aligned as 3 columns and 2 rows in a RadioGroup, so 6 RB-s in RG. If user selects a RB, right under it image1 and text1 are shown and under alternated RB-s image1 and text2 are also shown. User may select any RB. The proper behavior looks like that https://photos.app.goo.gl/NEqTaxsY6daxD3kJA
<android.support.design.widget.CoordinatorLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#color/bg">
<include layout="#layout/app_bar" />
<fragment
android:id="#+id/refreshLayoutFragment"
class="kz.fingram.RefreshLayoutFragment"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:layout_behavior="#string/appbar_scrolling_view_behavior"
tools:layout="#layout/fragment_refresh_layout" />
<LinearLayout
android:id="#+id/root"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:paddingEnd="#dimen/activity_margin"
android:paddingLeft="#dimen/activity_margin"
android:paddingRight="#dimen/activity_margin"
android:paddingStart="#dimen/activity_margin"
android:paddingTop="#dimen/activity_margin"
app:layout_behavior="#string/appbar_scrolling_view_behavior">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1"
android:orientation="vertical">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/when_u_want_money"
android:textAppearance="#style/TextAppearance.Medium" />
<RadioGroup
android:id="#+id/months"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="10dp"
android:background="#drawable/primary_transparent_round_bg"
android:orientation="horizontal"
app:setOnCheckedChangeListener="#{viewModel.mMonthOnCheckedChangeListener}" />
<LinearLayout
android:id="#+id/thisIs"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="3dp"
android:orientation="horizontal" />
<RadioGroup
android:id="#+id/months2"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="10dp"
android:background="#drawable/primary_transparent_round_bg"
android:orientation="horizontal"
app:setOnCheckedChangeListener="#{viewModel.mMonthOnCheckedChangeListener2}" />
<LinearLayout
android:id="#+id/thatIs"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="3dp"
android:orientation="horizontal" />
<Button
style="#style/Button.Primary"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="8dp"
android:enabled="#{viewModel.mIsNextEnabled}"
android:onClick="#{viewModel::nextOnClick}"
android:text="#string/next" />
</LinearLayout>
</android.support.design.widget.CoordinatorLayout>
Java code:
RadioGroup rg1 = findViewById(R.id.months);
rg1.setOnCheckedChangeListener(null);
rg1.clearCheck();
rg1.setOnCheckedChangeListener(mMonthOnCheckedChangeListener);
View view = radioGroup.findViewById(i);
if (view != null) {
mMonth = (TeamFreeMonth) view.getTag();
}
selectMonth();
checkButtonsState();
public final class OptionsActivity extends BaseAppCompatActivity {
private ActivityOptionsBinding mBinding;
public static void show(#NonNull final Context ctx) {
StorageHelper.getInstance().setInvited(false);
BaseAppCompatActivity.show(ctx, OptionsActivity.class, true, false);
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mBinding = DataBindingUtil.setContentView(this, R.layout.activity_options);
setupToolbar();
mBinding.setViewModel(new ViewModel());
}
public final class ViewModel extends BaseObservable {
private static final int TERM_6_MONTH_ID = 1;
private static final int INSTALLMENT_10000_ID = 1;
private final RefreshLayoutFragment mRefreshLayout;
public boolean mIsNextEnabled;
public TeamFreeMonth mMonth;
private TeamFreeMonth[] mMonths;
ViewModel() {
mMonth = null;
mMonths = null;
mRefreshLayout = (RefreshLayoutFragment) getSupportFragmentManager()
.findFragmentById(R.id.refreshLayoutFragment);
mRefreshLayout.setup(mBinding.root, new RefreshLayoutFragment.Callback() {
#Override
public void reload() {
try {
loadData();
} catch (Exception e) {
ExceptionHelper.displayException(OptionsActivity.this, e);
}
}
});
public RadioGroup.OnCheckedChangeListener mMonthOnCheckedChangeListener =
new RadioGroup.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(RadioGroup radioGroup, #IdRes int i) {
if (i != -1) {
RadioGroup rg2 = findViewById(R.id.months2);
rg2.setOnCheckedChangeListener(null);
rg2.clearCheck();
rg2.setOnCheckedChangeListener(mMonthOnCheckedChangeListener2);
View view = radioGroup.findViewById(i);
if (view != null) {
mMonth = (TeamFreeMonth) view.getTag();
}
selectMonth();
checkButtonsState();
}
}
};
public RadioGroup.OnCheckedChangeListener mMonthOnCheckedChangeListener2 =
new RadioGroup.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(RadioGroup radioGroup, #IdRes int i) {
if (i != -1) {
RadioGroup rg1 = findViewById(R.id.months);
rg1.setOnCheckedChangeListener(null);
rg1.clearCheck();
rg1.setOnCheckedChangeListener(mMonthOnCheckedChangeListener);
View view = radioGroup.findViewById(i);
if (view != null) {
mMonth = (TeamFreeMonth) view.getTag();
}
selectMonth();
checkButtonsState();
}
}
};
private void refreshMonths() {
mBinding.months.removeAllViews();
mBinding.months.clearCheck();
mBinding.months2.removeAllViews();
mBinding.months2.clearCheck();
mBinding.thisIs.removeAllViews();
mBinding.thatIs.removeAllViews();
final TeamFreeMonth oldMonth = mMonth;
mMonth = null;
checkButtonsState();
if (mMonths == null) {
return;
}
final TeamFreeMonth[] months = mMonths;
if (months.length == 0) {
return;
}
int halfMonths = months.length / 2;
for (int i = 0; i < halfMonths; i++) {
final String date = UtilitiesHelper.dateToStr(months[i].getDate(), Constants.DATE_FORMAT_LLLL);// Получили месяц от даты
final String date2 = UtilitiesHelper.dateToStr(months[i + halfMonths].getDate(), Constants.DATE_FORMAT_LLLL);// Получили месяц от даты
if (TextUtils.isEmpty(date) || TextUtils.isEmpty(date2)) {
continue;
}
final RadioButton rb = (RadioButton) LayoutInflater.from(OptionsActivity.this).inflate(R.layout.radio_button_tab, mBinding.months, false);
rb.setId(i);
rb.setTag(months[i]);
final SpannableString btnCaption = new SpannableString(date);
btnCaption.setSpan(new AbsoluteSizeSpan(getResources().getDimensionPixelSize(R.dimen.font_size_18)), 0, date.length(), 0);
rb.setText(btnCaption);
final RadioButton rb2 = (RadioButton) LayoutInflater.from(OptionsActivity.this).inflate(R.layout.radio_button_tab, mBinding.months2, false);
rb2.setId(i + halfMonths);
rb2.setTag(months[i + halfMonths]);
final SpannableString btnCaption2 = new SpannableString(date2);
btnCaption2.setSpan(new AbsoluteSizeSpan(getResources().getDimensionPixelSize(R.dimen.font_size_18)), 0, date2.length(), 0);
rb2.setText(btnCaption2);
if (i == 0) {
rb.setBackgroundResource(R.drawable.ll_radio_button_start);
rb2.setBackgroundResource(R.drawable.ll_radio_button_start);
} else if (i == halfMonths - 1) {
rb.setBackgroundResource(R.drawable.ll_radio_button_end);
rb2.setBackgroundResource(R.drawable.ll_radio_button_end);
}
mBinding.months.addView(rb);
mBinding.months2.addView(rb2);
TextView thisIs = (TextView) LayoutInflater.from(OptionsActivity.this).inflate(R.layout.options_this_is_item, mBinding.thisIs, false);
thisIs.setId(rb.getId());
thisIs.setText(getString(R.string.thisIs));
thisIs.setVisibility(View.INVISIBLE);
mBinding.thisIs.addView(thisIs);
TextView thatIs = (TextView) LayoutInflater.from(OptionsActivity.this).inflate(R.layout.options_that_is_item, mBinding.thatIs, false);
thatIs.setId(rb2.getId());
thatIs.setText(getString(R.string.thatIs));
thatIs.setVisibility(View.INVISIBLE);
mBinding.thatIs.addView(thatIs);
if (oldMonth != null && UtilitiesHelper.isDateEquals(oldMonth.getDate(), months[i].getDate())) {
mBinding.months.check(rb.getId());
mBinding.months2.check(rb2.getId());
}
}
selectMonth();
}
private void selectMonth()
{
int selectedId1 = mBinding.months.getCheckedRadioButtonId();
int selectedId = selectedId1 !=-1 ? selectedId1 : mBinding.months2.getCheckedRadioButtonId();
int n = mBinding.months.getChildCount();
List<TextView> views = new ArrayList<TextView>();
for (int i = 0; i < n; i++) {
views.add(i, (TextView) mBinding.thisIs.getChildAt(i));
views.add(i+3, (TextView) mBinding.thatIs.getChildAt(i));
}
int length = views.size();
for (int i = 0; i < length; i++) {
TextView child = views.get(i);
}
private void checkButtonsState() {
mIsNextEnabled = mMonth != null;
notifyChange();
}
public void nextOnClick(final View view) {
try {
final TeamFreeMonth[] months = mMonths;
if (mMonth == null || months == null || months.length == 0) {
throw new Exception(getString(R.string.enter_month));
}
SettingsHelper.setTermId(OptionsActivity.this, TERM_6_MONTH_ID);//
SettingsHelper.setTermRateId(OptionsActivity.this, mMonth.getTermRateId());//
SettingsHelper.setInstallmentId(OptionsActivity.this, INSTALLMENT_10000_ID);
SettingsHelper.setGoalDateInMillis(OptionsActivity.this, mMonth.getDate().getTime());//дата получения
SettingsHelper.setFirstGoalDateInMillis(OptionsActivity.this, months[0].getDate().getTime());
SettingsHelper.setGoalSum(OptionsActivity.this, mMonth.getSum());
BaseAppCompatActivity.show(OptionsActivity.this, SetGoalActivity.class, true, false);
} catch (Exception e) {
ExceptionHelper.displayException(OptionsActivity.this, e);
}
}
private void loadData() {
try {
final AsyncTask<Void, Void, TeamFreeMonth[]> task = new AsyncTask<Void, Void, TeamFreeMonth[]>() {
private Exception mError = null;
#Override
protected void onPreExecute() {
mRefreshLayout.setRefreshing(true);
}
#Override
protected TeamFreeMonth[] doInBackground(Void... params) {
try {
TeamFreeMonth[] months = ServerHelper.getInstance().syncGetOptionMonths(OptionsActivity.this, TERM_6_MONTH_ID, INSTALLMENT_10000_ID);
if (months != null && months.length > 0)
return months;
} catch (Exception e) {
mError = e;
}
return null;
}
#Override
protected void onPostExecute(TeamFreeMonth[] result) {
try {
if (mError != null) {
throw mError;
}
mMonths = result;
refreshMonths();
checkButtonsState();
mRefreshLayout.setRefreshing(false);
} catch (Exception e) {
mRefreshLayout.setError(e);
}
}
};
task.execute();
} catch (Exception e) {
mRefreshLayout.setError(e);
}
}
}
}
Image1 is always the same, while text1 and text2 differ. Text1 'You' is shown under the selected RB and text2 'Your friend' - under alternating RB-s.
The quetion still is how to show/hide image1 and text 1 or text 2 alternatively?
I can show/hide image1 and text-s under RB-s which is in the same column, but not alternating RB-s.
I am having a problem with cardview not displaying some from the database.
My app connects to a grails back end which has a PostgreSQL db.
I have a cardview inside a recyclerview. It receives 7 values in form of JSON but on running the app, only 5 are displayed. I try doing System.out of the JSON in the stack trace and I find that all the 7 values are received so everything is okay on that front.
For clarity purposes, the fields that are not being displayed are labs("labs") and drugs administered("drugsAdministered").
Here is the main class(ClinicalHistory.java), the adapter class, the xml and the stack-trace.
ClinicalHistory.java
public class ClinicalHistory extends AppCompatActivity {
RecyclerView clinicalHistory_rv;
SwipeRefreshLayout swipeRefreshLayout;
List<com.example.user.eafya.models.ClinicalHistory> clinicalHistory_List;
com.example.user.eafya.models.ClinicalHistory clinicalHistory;
ClinicalHistoryAdapter clinicalHistoryAdapter;
private StringRequest clinicalHistoryRequest;
private LinearLayout no_data;
private LinearLayoutManager linearLayoutManager;
private RequestQueue requestQueue;
private ProgressDialog pb;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_clinical_history);
initWidgets();
fetchData();
}
private void fetchData() {
pb = new ProgressDialog(this);
pb.setIcon(R.mipmap.ic_launcher);
pb.setTitle("Please wait");
pb.setCancelable(false);
pb.setMessage("Loading data..");
pb.show();
clinicalHistoryRequest = new StringRequest(Request.Method.GET, Configs.URL_LOGIN + Configs.CLINICALHISTORY_PATH, new Response.Listener<String>() {
#Override
public void onResponse(String result) {
pb.dismiss();
System.out.print("======================================"+ result);
try {
JSONObject jsonObject = new JSONObject(result);
JSONArray jsonArray = jsonObject.getJSONArray("mVisit");
for (int i=0;i<jsonArray.length();i++){
System.out.print("----------------"+jsonArray.getJSONObject(i).getString("labs"));
}
Log.d("myError: ", String.valueOf(jsonArray.length()));
if(jsonArray.length()<1) {
clinicalHistory_List.clear();
no_data.setVisibility(View.VISIBLE);
}else if( jsonArray.length()>0){
if(no_data.getVisibility()==View.VISIBLE){
no_data.setVisibility(View.GONE);
}
for(int i=0 ; i<jsonArray.length() ; i++){
JSONObject data = jsonArray.getJSONObject(i);
clinicalHistory = new com.example.user.eafya.models.ClinicalHistory();
clinicalHistory.setDate(data.getString("dateCreated"));
clinicalHistory.setHospital(data.getString("hospitalAttended"));
clinicalHistory.setDoctor(data.getString("attendingDoctor"));
clinicalHistory.setLabs(data.getString("labs"));
clinicalHistory.setChiefComplains(data.getString("chiefComplains"));
clinicalHistory.setDrugs(data.getString("drugsAdministered"));
clinicalHistory_List.add(clinicalHistory);
}
clinicalHistoryAdapter = new ClinicalHistoryAdapter(ClinicalHistory.this, clinicalHistory_List);
linearLayoutManager = new LinearLayoutManager(ClinicalHistory.this);
clinicalHistory_rv.setLayoutManager(linearLayoutManager);
clinicalHistory_rv.setItemAnimator(new DefaultItemAnimator());
clinicalHistory_rv.setAdapter(clinicalHistoryAdapter);
clinicalHistory_rv.setSaveEnabled(true);
clinicalHistory_rv.setSaveFromParentEnabled(true);
clinicalHistoryAdapter.notifyDataSetChanged();
}
} catch (JSONException e) {
Log.d("MaeraJ",e.toString());
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError volleyError) {
pb.dismiss();
AlertDialog.Builder dialog = new AlertDialog.Builder(ClinicalHistory.this);
dialog.setTitle("Something went wrong !!");
dialog.setCancelable(true);
dialog.setIcon(R.mipmap.ic_launcher);
dialog.setMessage("Check your data connection");
dialog.setPositiveButton("RETRY", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
//retry
dialogInterface.dismiss();
fetchData();
}
});
dialog.setNegativeButton("CANCEL", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
//cancel
dialogInterface.dismiss();
}
});
dialog.create();
dialog.show();
Log.d("Maera",volleyError.toString());
}
});
requestQueue.add(clinicalHistoryRequest);
}
private void initWidgets() {
requestQueue = Volley.newRequestQueue(this);
no_data = findViewById(R.id.nodata_LY);
clinicalHistory_rv = findViewById(R.id.clinicalHistory_RV);
clinicalHistory_List = new ArrayList<>();
swipeRefreshLayout = findViewById(R.id.swipeContainer);
swipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
#Override
public void onRefresh() {
refresh();
}
});
}
private void refresh() {
try {
clinicalHistory_List.clear();
fetchData();
swipeRefreshLayout.setRefreshing(false);
} catch (Exception e) {
e.printStackTrace();
}
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch(item.getItemId()){
case R.id.home:
onBackPressed();
break;
}
return super.onOptionsItemSelected(item);
}
}
Adapter class(ClinicalHistoryAdapter.java)
public class ClinicalHistoryAdapter extends RecyclerView.Adapter<ClinicalHistoryAdapter.myViewHolder> {
Context ctx;
List<ClinicalHistory> clinicalHistoryList;
ClinicalHistory clinicalHistoryModel;
LayoutInflater inflater;
public ClinicalHistoryAdapter(Context ctx, List<ClinicalHistory> clinicalHistoryList) {
this.ctx = ctx;
this.clinicalHistoryList = clinicalHistoryList;
inflater = LayoutInflater.from(ctx);
}
public class myViewHolder extends RecyclerView.ViewHolder {
TextView clinicalHist_date_TV,clinicalHist_hospital, clinicalHist_doctor,clinicalHist_chiefComplains, clinicalHist_labs, clinicalHist_drugs;
ImageView clinicalHist_img;
public myViewHolder(View itemView) {
super(itemView);
clinicalHist_img = itemView.findViewById(R.id.clinicalHist_image_IV);
clinicalHist_date_TV = itemView.findViewById(R.id.clinicalHist_date__TV);
clinicalHist_hospital = itemView.findViewById(R.id.clinicalHist_hospital_TV);
clinicalHist_doctor = itemView.findViewById(R.id.clinicalHist_doctor);
clinicalHist_chiefComplains = itemView.findViewById(R.id.clinicalHist_chief_complains_TV);
clinicalHist_labs = itemView.findViewById(R.id.clinicalHist_labs_TV);
clinicalHist_drugs = itemView.findViewById(R.id.clinicalHist_drugs_TV);
}
}
#Override
public ClinicalHistoryAdapter.myViewHolder onCreateViewHolder(ViewGroup viewGroup, int i) {
View my_view = inflater.inflate(R.layout.clinical_history_item,viewGroup,false);
return new myViewHolder(my_view);
}
#Override
public void onBindViewHolder(ClinicalHistoryAdapter.myViewHolder myViewHolder, final int position) {
clinicalHistoryModel = new ClinicalHistory();
clinicalHistoryModel = clinicalHistoryList.get(position);
myViewHolder.clinicalHist_date_TV.setText(clinicalHistoryModel.getDate());
myViewHolder.clinicalHist_hospital.setText(clinicalHistoryModel.getHospital());
myViewHolder.clinicalHist_doctor.setText(clinicalHistoryModel.getDoctor());
myViewHolder.clinicalHist_chiefComplains.setText(clinicalHistoryModel.getChiefComplains());
myViewHolder.clinicalHist_labs.setText(clinicalHistoryModel.getLabs());
myViewHolder.clinicalHist_drugs.setText(clinicalHistoryModel.getDrugs());
myViewHolder.clinicalHist_doctor.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
goToDetails(position);
}
});
myViewHolder.clinicalHist_hospital.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
goToDetails(position);
}
});
Glide.with(ctx).load(clinicalHistoryModel.getImg()).placeholder(R.drawable.loader).error(R.drawable.header).into(myViewHolder.clinicalHist_img);
}
private void goToDetails(int pos) {
clinicalHistoryModel = clinicalHistoryList.get(pos);
Intent intent = new Intent(ctx,MedicalDetailActivity.class);
intent.putExtra("dateCreated", clinicalHistoryModel.getDate());
intent.putExtra("clinicalHist_img", clinicalHistoryModel.getImg());
intent.putExtra("hospitalAttended", clinicalHistoryModel.getHospital());
intent.putExtra("attendingDoctor", clinicalHistoryModel.getDoctor());
intent.putExtra("chiefComplaints", clinicalHistoryModel.getChiefComplains());
intent.putExtra("labs", clinicalHistoryModel.getLabs());
intent.putExtra("drugs", clinicalHistoryModel.getLabs());
ctx.startActivity(intent);
}
#Override
public int getItemCount() {
return clinicalHistoryList.size();
}
}
The xml file
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="wrap_content"
android:padding="4dp">
<android.support.v7.widget.CardView
android:layout_width="match_parent"
android:layout_height="wrap_content"
>
<LinearLayout
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<LinearLayout
android:layout_margin="2dp"
android:orientation="horizontal"
android:padding="2dp"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<ImageView
android:id="#+id/clinicalHist_image_IV"
android:layout_width="110dp"
android:layout_height="80dp"
android:layout_gravity="top"
android:scaleType="fitXY"
android:src="#drawable/header" />
<LinearLayout
android:padding="4dp"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<TextView
android:textAlignment="textStart"
android:layout_gravity="start"
android:id="#+id/clinicalHist_date__TV"
android:text="21/09/2012"
android:textColor="#color/colorAccent"
android:textAppearance="#android:style/TextAppearance.DeviceDefault.Medium"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
<TextView
android:textAlignment="textStart"
android:layout_gravity="start"
android:id="#+id/clinicalHist_hospital_TV"
android:text="Hema Hospital"
android:textColor="#color/colorAccent"
android:textAppearance="#android:style/TextAppearance.DeviceDefault.Medium"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="start"
android:id="#+id/clinicalHist_doctor"
android:text="Dr.Lilian"/>
<TextView
android:layout_gravity="center"
android:id="#+id/clinicalHist_labs_TV"
android:text=" Brucella "
android:textColor="#000"
android:textAppearance="#android:style/TextAppearance.DeviceDefault.Medium"
android:layout_width="match_parent"
android:layout_height="match_parent" />
<TextView
android:layout_gravity="center"
android:id="#+id/clinicalHist_chief_complains_TV"
android:text=" Headache "
android:textColor="#000"
android:textAppearance="#android:style/TextAppearance.DeviceDefault.Medium"
android:layout_width="match_parent"
android:layout_height="match_parent" />
<TextView
android:layout_gravity="center"
android:id="#+id/clinicalHist_drugs_TV"
android:text=" Brufen "
android:textColor="#000"
android:textAppearance="#android:style/TextAppearance.DeviceDefault.Medium"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</LinearLayout>
</LinearLayout>
</LinearLayout>
</android.support.v7.widget.CardView>
</LinearLayout>
The stack trace
I/System.out: ======================================{"mVisit":[{"id":1,"chiefComplains":"Headache","dateCreated":"2017-08-11T21:00:00Z","labs":"Brucella","hospitalAttended":"Hema Hospital","drugsAdministered":"Tramadol","attendingDoctor":"Dr. Kisinga"
I have found the solution. The problem was in the model.
This was my previous model. Note the parameters in the
setDrugs() and setLabs().
public class ClinicalHistory {
String img;
String date;
String labs;
String hospital;
String chiefComplains;
String doctor;
String drugs;
public ClinicalHistory() {
}
public String getImg() {
return img;
}
public void setImg(String img) {
this.img = img;
}
public String getHospital() {
return this.hospital = hospital ;
}
public void setHospital(String hospital) {
this.hospital = hospital;
}
public String getChiefComplains(){return this.chiefComplains = chiefComplains;}
public void setChiefComplains(String chiefComplains){ this.chiefComplains = chiefComplains;}
public String getLabs() {
return this.labs = labs ;
}
public void setLabs(String hospital) {
this.labs = labs;
}
public String getDoctor() {
return this.doctor = doctor ;
}
public void setDoctor(String doctor) {
this.doctor = doctor;
}
public void setDrugs(String hospital) {
this.drugs = drugs;
}
public String getDrugs() {
return this.drugs = drugs ;
}
public void setDate(String date) {
this.date = date;
}
public String getDate() {
return date;
}
}
After I made this change it worked
public class ClinicalHistory {
String img;
String date;
String labs;
String hospital;
String chiefComplains;
String doctor;
String drugs;
public ClinicalHistory() {
}
public String getImg() {
return img;
}
public void setImg(String img) {
this.img = img;
}
public String getHospital() {
return this.hospital = hospital ;
}
public void setHospital(String hospital) {
this.hospital = hospital;
}
public String getChiefComplains(){return this.chiefComplains = chiefComplains;}
public void setChiefComplains(String chiefComplains){ this.chiefComplains = chiefComplains;}
public String getLabs() {
return this.labs = labs ;
}
public void setLabs(String labs) {
this.labs = labs;
}
public String getDoctor() {
return this.doctor = doctor ;
}
public void setDoctor(String doctor) {
this.doctor = doctor;
}
public void setDrugs(String drugs) {
this.drugs = drugs;
}
public String getDrugs() {
return this.drugs = drugs ;
}
public void setDate(String date) {
this.date = date;
}
public String getDate() {
return date;
}
}
More than one value is received but when I am parsing the JSON into Android, it is only showing the first value.
Here is the JsonNew.php file:
require "index.php";
$user_shopID = $_POST["UniqueKey"] ;
$sql_query="Select * from products where ShopID like '$user_shopID';";
$result = mysqli_query($con, $sql_query);
$response = array();
while ($row = mysqli_fetch_array($result))
{
array_push($response,array("ProductID"=>$row[0],"Product Name"=>$row[1], "Buying Price"=>$row[3], "Selling Price"=>$row[4]));
}
echo json_encode(array("server_response"=>$response));
mysqli_close($con);
This is the ContactAdapters.java:
public class ContactAdapter extends ArrayAdapter {
List list = new ArrayList();
public ContactAdapter(#NonNull Context context, #LayoutRes int resource) {
super(context, resource);
}
public void add(Contacts object) {
super.add(object);
list.add(object);
}
#Override
public int getCount() {
return list.size();
}
#Nullable
#Override
public Object getItem(int position) {
return list.get(position);
}
#NonNull
#Override
public View getView(int position, #Nullable View convertView, #NonNull ViewGroup parent) {
View row;
row = convertView;
ContactHolder contactHolder;
if (row == null) {
LayoutInflater layoutInflater = (LayoutInflater) this.getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
row = layoutInflater.inflate(R.layout.row_layout, parent, false);
contactHolder = new ContactHolder();
contactHolder.tx_id = (TextView) row.findViewById(R.id.id);
contactHolder.tx_name = (TextView) row.findViewById(R.id.name);
contactHolder.tx_buy = (TextView) row.findViewById(R.id.buy);
contactHolder.tx_sell = (TextView) row.findViewById(R.id.sell);
row.setTag(contactHolder);
} else {
contactHolder = (ContactHolder) row.getTag();
}
Contacts contacts = (Contacts) this.getItem(position);
contactHolder.tx_id.setText(contacts.getId());
contactHolder.tx_name.setText(contacts.getName());
contactHolder.tx_buy.setText(contacts.getBuy());
contactHolder.tx_sell.setText(contacts.getSell());
return row;
}
static class ContactHolder {
TextView tx_id, tx_name, tx_buy, tx_sell;
}
}
And this the row_layout.xml
android:layout_width="match_parent"
android:layout_height="75dp"
xmlns:app="http://schemas.android.com/apk/res-auto">
<TextView
android:id="#+id/id"
android:layout_width="100dp"
android:layout_height="match_parent"
android:layout_alignParentLeft="true"
android:text="TextView"
android:gravity="center"
android:textColor="#000000"
android:layout_below="#+id/textView13" />
<TextView
android:id="#+id/name"
android:layout_width="120dp"
android:layout_height="match_parent"
android:layout_toRightOf="#+id/id"
android:text="TextView"
android:gravity="center"
android:textColor="#000000"
android:layout_below="#+id/textView14" />
<TextView
android:id="#+id/buy"
android:layout_width="100dp"
android:layout_height="match_parent"
android:text="TextView"
android:gravity="center"
android:textColor="#000000"
android:layout_toRightOf="#+id/name"
android:layout_toEndOf="#+id/name"
android:layout_alignTop="#+id/name" />
<TextView
android:id="#+id/sell"
android:layout_width="100dp"
android:layout_height="match_parent"
android:layout_toRightOf="#+id/buy"
android:text="TextView"
android:gravity="center"
android:textColor="#000000"
android:layout_alignTop="#+id/buy"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true" />
Here is DisplayProductsListview.java
listview = (ListView) findViewById(R.id.listview);
contactAdapter = new ContactAdapter(this,R.layout.row_layout);
listview.setAdapter(contactAdapter);
json_string = getIntent().getExtras().getString("json_data");
try {
jsonObject = new JSONObject(json_string);
jsonArray = jsonObject.getJSONArray("server_response");
int count=0;
String id, name, buy, sell;
while (count<jsonObject.length()){
JSONObject JO = jsonArray.getJSONObject(count);
id = JO.getString("ProductID");
name = JO.getString("Product Name");
buy = JO.getString("Buying Price");
sell = JO.getString("Selling Price");
Contacts contacts = new Contacts(id,name,buy,sell);
contactAdapter.add(contacts);
count++;
}
} catch (JSONException e) {
e.printStackTrace();
}
}
Here is the Contacts.java
private String id, name, buy, sell;
public Contacts(String id, String name, String buy, String sell){
this.setId(id);
this.setName(name);
this.setBuy(buy);
this.setSell(sell);
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getBuy() {
return buy;
}
public void setBuy(String buy) {
this.buy = buy;
}
public String getSell() {
return sell;
}
public void setSell(String sell) {
this.sell = sell;
}
}
When I am getting the JSON datas from the server, they are coming perfectly, but when I am making them display in a list view those datas are not coming. Only the first data and his values are coming into the list view.
Here are the Screenshots:
Here you will See what is actually happening with me
In the contactAdapter class you have to create a ArrayList.
ArrayList<Contact> arrayList = new ArrayList<>();
Somewhat you have to do like this.
change this function
while (count<jsonArray.length()){
JSONObject JO = jsonArray.getJSONObject(count);
id = JO.getString("ProductID");
name = JO.getString("Product Name");
buy = JO.getString("Buying Price");
sell = JO.getString("Selling Price");
Contacts contacts = new Contacts(id,name,buy,sell);
contactAdapter.add(contacts);
count++;
}
you have to use jsonarray length not the object length.
I followed this tutorial to import database. Then I try to read the data using ArrayList to display them in listview. But I got nullpointer exception on my rawQuery saying it is invoking a null object reference.
DB.java
public class DB extends SQLiteOpenHelper {
//The Android's default system path of your application database.
private static String DB_PATH = "data/data/hairulhazri.malayforyou/databases/";
private static String DB_NAME = "malayforyou";
private static String TABLE_LOCATION = "Frasa";
private final Context context;
private SQLiteDatabase db;
// constructor
public DB(Context context) {
super( context , DB_NAME , null , 1);
this.context = context;
}
// Creates a empty database on the system and rewrites it with your own database.
public void create() throws IOException {
boolean dbExist = checkDataBase();
if(dbExist){
//do nothing - database already exist
}else{
// By calling this method and empty database will be created into the default system path
// of your application so we are gonna be able to overwrite that database with our database.
this.getReadableDatabase();
try {
copyDataBase();
} catch (IOException e) {
throw new Error("Error copying database");
}
}
}
// Check if the database exist to avoid re-copy the data
private boolean checkDataBase(){
SQLiteDatabase checkDB = null;
try{
String path = DB_PATH + DB_NAME;
checkDB = SQLiteDatabase.openDatabase(path, null, SQLiteDatabase.OPEN_READONLY);
}catch(SQLiteException e){
// database don't exist yet.
e.printStackTrace();
}
if(checkDB != null){
checkDB.close();
}
return checkDB != null ? true : false;
}
// copy your assets db to the new system DB
private void copyDataBase() throws IOException{
//Open your local db as the input stream
InputStream myInput = context.getAssets().open(DB_NAME);
// Path to the just created empty db
String outFileName = DB_PATH + DB_NAME;
//Open the empty db as the output stream
OutputStream myOutput = new FileOutputStream(outFileName);
//transfer bytes from the inputfile to the outputfile
byte[] buffer = new byte[1024];
int length;
while ((length = myInput.read(buffer))>0){
myOutput.write(buffer, 0, length);
}
//Close the streams
myOutput.flush();
myOutput.close();
myInput.close();
}
//Open the database
public boolean open() {
try {
String myPath = DB_PATH + DB_NAME;
db = SQLiteDatabase.openDatabase(myPath, null, SQLiteDatabase.OPEN_READWRITE);
return true;
} catch(SQLException sqle) {
db = null;
return false;
}
}
#Override
public synchronized void close() {
if(db != null)
db.close();
super.close();
}
#Override
public void onCreate(SQLiteDatabase db) {
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
}
// PUBLIC METHODS TO ACCESS DB CONTENT
// -----------------------------------------------------------------------------------------------------------------
public ArrayList<Frasa> getFrasa(String situation) {
//ArrayList of Frasa class objects
ArrayList<Frasa> arrFrasa = null;
//String query = "SELECT * FROM Frasa WHERE Situation = " + situation;
String selectQuery = "SELECT " +
Frasa.KEY_ID + "," +
Frasa.KEY_PHRASE + "," +
Frasa.KEY_TRANSLATE + "," +
Frasa.KEY_PRONOUNCE +
" FROM " + TABLE_LOCATION + " WHERE situation = " +situation;
db = SQLiteDatabase.openDatabase( DB_PATH + DB_NAME , null, SQLiteDatabase.OPEN_READWRITE);
Cursor curFrasa = db.rawQuery(selectQuery, null);
if (curFrasa != null && curFrasa.moveToFirst()) {
arrFrasa = new ArrayList<Frasa>();
while (curFrasa.isAfterLast() == false) {
//Frasa is a class with list of fields
Frasa fra = new Frasa();
fra.setId(curFrasa.getInt(curFrasa.getColumnIndex(Frasa.KEY_ID)));
fra.setPhrase(curFrasa.getString(curFrasa.getColumnIndex(Frasa.KEY_PHRASE)));
fra.setTranslate(curFrasa.getString(curFrasa.getColumnIndex(Frasa.KEY_TRANSLATE)));
fra.setPronounce(curFrasa.getString(curFrasa.getColumnIndex(Frasa.KEY_PRONOUNCE)));
arrFrasa.add(fra);
curFrasa.moveToNext();
}
}
curFrasa.close();
db.close();
return arrFrasa;
}
}
Frasa.java (Database table and columns)
public class Frasa {
// Labels Table Columns names
public static final String KEY_ID = "id";
public static final String KEY_PHRASE = "phrase";
public static final String KEY_TRANSLATE = "translate";
public static final String KEY_PRONOUNCE = "pronounce";
// property help us to keep data
public int id;
public String situation;
public String phrase;
public String translate;
public String pronounce;
public Frasa() {
}
public Frasa(int id, String situation, String phrase, String translate, String pronounce) {
this.id = id;
this.situation = situation;
this.phrase = phrase;
this.translate = translate;
this.pronounce = pronounce;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getPhrase() {
return phrase;
}
public void setPhrase(String phrase) {
this.phrase = phrase;
}
public String getTranslate() {
return translate;
}
public void setTranslate(String translate) {
this.translate = translate;
}
public String getPronounce() {
return pronounce;
}
public void setPronounce(String pronounce) {
this.pronounce = pronounce;
}
}
public class GreetingAdapter extends ArrayAdapter<Frasa> {
Context context;
int layoutResourceId;
ArrayList<Frasa> data = new ArrayList<Frasa>();
public GreetingAdapter(Context context, int layoutResourceId, ArrayList<Frasa> data)
{
super(context, layoutResourceId, data);
this.layoutResourceId = layoutResourceId;
this.context = context;
this.data = data;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View row = convertView;
UserHolder holder = null;
if (row == null) {
LayoutInflater inflater = ((Activity) context).getLayoutInflater();
row = inflater.inflate(layoutResourceId, parent, false);
holder = new UserHolder();
holder.textPhrase = (TextView) row.findViewById(R.id.textViewPhrase);
holder.textTranslate = (TextView) row.findViewById(R.id.textViewTranslate);
holder.btnSpeak = (Button) row.findViewById(R.id.buttonSpeak);
holder.btnRecord = (Button) row.findViewById(R.id.buttonRecord);
holder.btnPlay = (Button) row.findViewById(R.id.buttonPlay);
row.setTag(holder);
} else {
holder = (UserHolder) row.getTag();
}
Frasa frasa = data.get(position);
holder.textPhrase.setText(frasa.getPhrase());
holder.textTranslate.setText(frasa.getTranslate());
holder.btnSpeak.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Log.i("Edit Button Clicked", "**********");
Toast.makeText(context, "Speak button Clicked",
Toast.LENGTH_LONG).show();
}
});
holder.btnRecord.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Log.i("Delete Button Clicked", "**********");
Toast.makeText(context, "Delete button Clicked",
Toast.LENGTH_LONG).show();
}
});
holder.btnPlay.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Log.i("Play Button Clicked", "**********");
Toast.makeText(context, "Playing recorded audio",
Toast.LENGTH_LONG).show();
}
});
return row;
}
static class UserHolder {
TextView textPhrase;
TextView textTranslate;
Button btnSpeak;
Button btnRecord;
Button btnPlay;
}
}
activity_list_greetings.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:id="#+id/txt_header"
android:layout_width="match_parent"
android:layout_height="48dp"
android:layout_centerHorizontal="true"
android:gravity="center"
android:text="Greetings"
android:textAppearance="?android:attr/textAppearanceLarge"
android:textColor="#android:color/black" />
<ListView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/listGreetings"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true"
android:layout_below="#+id/txt_header" />
list_item_greet.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:id="#+id/textViewPhrase"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Phrase"
android:textAppearance="?android:attr/textAppearanceLarge"
android:layout_above="#+id/buttonRecord"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true" />
<Button
android:id="#+id/buttonSpeak"
android:layout_width="80dp"
android:layout_height="40dp"
android:layout_alignParentRight="true"
android:layout_alignParentTop="true"
android:background="#FFFFFF"
android:focusable="false"
android:focusableInTouchMode="false"
android:text="Speak"
android:textColor="#0099CC" />
<Button
android:id="#+id/buttonRecord"
android:layout_width="80dp"
android:layout_height="40dp"
android:layout_alignParentRight="true"
android:layout_below="#+id/buttonSpeak"
android:layout_marginTop="3dp"
android:background="#FFFFFF"
android:focusable="false"
android:focusableInTouchMode="false"
android:text="Record"
android:textColor="#0099CC" />
<Button
android:id="#+id/buttonPlay"
android:layout_width="80dp"
android:layout_height="40dp"
android:layout_alignParentRight="true"
android:layout_below="#+id/buttonRecord"
android:layout_marginTop="3dp"
android:background="#FFFFFF"
android:focusable="false"
android:focusableInTouchMode="false"
android:text="Play"
android:textColor="#0099CC" />
<TextView
android:id="#+id/textViewTranslate"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Translate"
android:textSize="20sp"
android:textColor="#color/background_material_dark"
android:layout_below="#+id/buttonRecord"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true" />
</RelativeLayout>
ListGreetings.java
public class ListGreetings extends ActionBarActivity {
TextView txtPhrase, txtTranslate;
Button speakButton;
MediaPlayer pronounce;
ListView userList;
GreetingAdapter greetAdapter;
//ArrayList<Frasa> frasaArray = new ArrayList<Frasa>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_list_greetings);
DB db = new DB(this);
db.open();
//get Frasa data
ArrayList<Frasa> frasaArray = db.getFrasa("Greetings");
/**
* set item into adapter
*/
greetAdapter = new GreetingAdapter(ListGreetings.this, R.layout.list_item_greet, frasaArray);
userList = (ListView) findViewById(R.id.listGreetings);
userList.setItemsCanFocus(false);
userList.setAdapter(greetAdapter);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_list_greetings, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
Is it my way of calling getFrasa wrong? Or the database cannot be detected? I'm sure I already pushed the database file to both assets folder & inside the package. Sorry, if I'm not formatting the codes correctly. Thanks in advance for any help.
The problem is that you are trying to open the Database from a different location
private static String DB_PATH = "data/data/hairulhazri.malayforyou/databases/";
private static String DB_NAME = "malayforyou";
...
...
db = SQLiteDatabase.openDatabase( DB_PATH + DB_NAME , null, SQLiteDatabase.OPEN_READWRITE);
db is returning NULL because your database is stored in /assets folder not in "data/data/hairulhazri.malayforyou/databases/"