I am not sure why, I have explored both .setValue() and .updateChildren() methods, but for whatever reason when I read data from firebase it is returning null. Here is how I write to Firebase:
Model Poll Class:
#IgnoreExtraProperties
public class Poll {
private String question;
private String image_URL;
public Poll() {
}
public Poll(String Question, String Image_URL) {
this.question = Question;
this.image_URL = Image_URL;
}
public String getQuestion() {
return question;
}
public void setQuestion(String question) {
this.question = question;
}
public String getImage_URL() {
return image_URL;
}
public void setImage_URL(String image_URL) {
this.image_URL = image_URL;
}
#Exclude
public Map<String, Object> toMap(){
HashMap<String, Object> result = new HashMap<>();
result.put("question", question);
result.put("image_URL", image_URL);
return result;
}
}
*I am following the documentation here with my .toMap() method and use of .updateChildren()
Here is where I create my Firebase references and write to the database:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_create);
mStorage = FirebaseStorage.getInstance();
mStorageRef = mStorage.getReferenceFromUrl("gs://firebase-fan-polls.appspot.com");
mBaseRef = FirebaseDatabase.getInstance().getReference();
mPollsRef = mBaseRef.child("Polls");
mAddImageButton = (FloatingActionButton) findViewById(R.id.add_image_button);
mAddAnswersButton = (ImageView) findViewById(R.id.add_answers_button);
mImagePreview = (ImageView) findViewById(R.id.preview_image);
mCreatePollQuestion = (EditText) findViewById(R.id.create_poll_question_editText);
mCreatePollAnswerCounter = (TextView) findViewById(R.id.create_poll_answer_counter_TextView);
mEditTextAnswerLayout = (ViewGroup) findViewById(R.id.create_poll_questions_answer_layout);
mSubmitPollCreation = (FloatingActionButton) findViewById(R.id.submit_poll_FAB);
mNumberOfPollAnswersCreatedByUser = 2;
mAnswerChoices = new ArrayList<>();
mCreatePollAnswerCounter.setText(String.valueOf(mNumberOfPollAnswersCreatedByUser));
for (int i = 0; i < mNumberOfPollAnswersCreatedByUser; i++) {
createAnswerChoice(i + 1);
}
mAddAnswersButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mNumberOfPollAnswersCreatedByUser++;
if (mNumberOfPollAnswersCreatedByUser > 5) {
Toast.makeText(getApplicationContext(), R.string.max_create_answers, Toast.LENGTH_SHORT).show();
return;
}
createAnswerChoice(mNumberOfPollAnswersCreatedByUser);
mCreatePollAnswerCounter.setText(String.valueOf(mNumberOfPollAnswersCreatedByUser));
}
});
mSubmitPollCreation.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//TODO: Need to check if poll requirements are added, i.e. Question, Answer, ......
//check if image has been loaded first
if (resultImageURL == null) {
Toast.makeText(getApplicationContext(), getResources().getString(R.string.no_image_selected), Toast.LENGTH_LONG).show();
return;
}
Poll poll = new Poll(mCreatePollQuestion.getText().toString(), resultImageURL);
Map <String, Object> pollMap = poll.toMap();
String key = mBaseRef.child("Polls").push().getKey();
Map<String, Object> childUpdates = new HashMap<String, Object>();
childUpdates.put("/Polls/" + key, pollMap);
mBaseRef.updateChildren(childUpdates);
if (mNumberOfPollAnswersCreatedByUser > 5) {
Toast.makeText(getApplicationContext(), getResources().getText(R.string.poll_answers_greater_than_five), Toast.LENGTH_LONG).show();
mNumberOfPollAnswersCreatedByUser = 5;
}
Intent toHomeActivity = new Intent(CreateActivity.this, HomeActivity.class);
toHomeActivity.putExtra("viewpager_position", 2);
startActivity(toHomeActivity);
}
});
Everything is writing to Firebase correctly, as I can see it in the database in my console. I try and read it from this activity:
public class PollFragment extends Fragment {
#Bind(R.id.comment_label_counter)
TextView mCommentCounter;
#Bind(R.id.comments_label_icon)
ImageView mCommentsLabelIcon;
private DatabaseReference mBaseRef;
private DatabaseReference mPollsRef;
private DatabaseReference mSelectedPollRef;
private RadioGroup mPollQuestionRadioGroup;
private RadioGroup.LayoutParams mParams;
//static
private TextView mCommentsLabel;
private TextView mTotalVoteCounter;
private TextView mSelectedVote;
private TextView mYourVotelabel;
private ViewPager mViewPager;
private int mPagerCurrentPosition;
private static final String VOTE_COUNT_LABEL = "Vote_Count";
private static final String QUESTION_LABEL = "question";
private static final String ANSWERS_LABEL = "Answers";
private static final String POLL_LABEL = "Poll";
private static final String IMAGE_URL = "image_URL";
//all date items; dynamic
private DateFormat mDateFormat;
private Date mDate;
private String mCurrentDateString;
private TextView mPollQuestion;
private ArrayList<RadioButton> mPollAnswerArrayList;
private HorizontalBarChart mPollResults;
ArrayList<BarEntry> pollResultChartValues;
private BarDataSet data;
private ArrayList<IBarDataSet> dataSets;
private ValueEventListener valueEventListener;
private String pollID;
private int mPollIndex;
private ProgressBar mProgressBar;
private OnFragmentInteractionListener mListener;
public PollFragment() {
// Required empty public constructor
}
/**
* Use this factory method to create a new instance of
* this fragment using the provided parameters.
*
* #return A new instance of fragment PollFragment.
*/
// TODO: Rename and change types and number of parameters
// TODO: Decide where to add comments button;
public static PollFragment newInstance(String pollIndex) {
PollFragment fragment = new PollFragment();
Bundle args = new Bundle();
args.putString("POLL_ID", pollIndex);
fragment.setArguments(args);
return fragment;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//TODO: check navigation to see if there are different ID's being generated from trending, following, and new fragments
Bundle args = getArguments();
String pollID = args.getString("POLL_ID");
Log.v("TAG", "THE PASSED ID Is " + pollID);
mBaseRef = FirebaseDatabase.getInstance().getReference();
mPollsRef = mBaseRef.child(POLL_LABEL);
mSelectedPollRef = mPollsRef.child(pollID);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// TODO: Add Fragment Code to check if savedInstanceState == null; add at Activity Level?
// Inflate the layout for this fragment
final ViewGroup rootView = (ViewGroup) inflater.inflate(R.layout.fragment_poll, container, false);
ButterKnife.bind(this, rootView);
getActivity().setTitle(R.string.todays_polls_title);
//Initialize Poll Results Bar Chart and set to Invisible
mPollResults = (HorizontalBarChart) rootView.findViewById(R.id.poll_results_chart);
mPollResults.setBackgroundColor(getResources().getColor(R.color.white));
mPollResults.setNoDataTextDescription(getResources().getString(R.string.no_results_description));
mPollResults.setVisibility(View.INVISIBLE);
mTotalVoteCounter = (TextView) rootView.findViewById(R.id.total_vote_counter);
mCommentCounter = (TextView) rootView.findViewById(R.id.comment_label_counter);
mCommentCounter = (TextView) rootView.findViewById(R.id.comment_label_counter);
mProgressBar = (ProgressBar) rootView.findViewById(R.id.progress_bar_white);
mPollQuestion = (TextView) rootView.findViewById(R.id.poll_question);
mPollQuestion.setTextSize(TypedValue.COMPLEX_UNIT_PX, getResources().getDimension(R.dimen.poll_question_text_size));
mPollQuestionRadioGroup = (RadioGroup) rootView.findViewById(R.id.poll_question_group);
mSelectedPollRef.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
Log.v("TAG", dataSnapshot.getKey());
//add question
String pollQuestion = (String) dataSnapshot.child(QUESTION_LABEL).getValue();
Log.v("TAG", "THE POLL QUESTION IS " + pollQuestion);
mPollQuestion.setText(pollQuestion);
mPollQuestion.setTypeface(null, Typeface.BOLD);
//add image
String pollImageURL = (String) dataSnapshot.child(IMAGE_URL).getValue();
Log.v("TAG", "THE POLL IMAGE URL IS" + pollImageURL);
Picasso.with(getActivity())
.load(pollImageURL)
.fit()
.placeholder(R.drawable.loading_spinner_white)
.into((ImageView) rootView.findViewById(R.id.poll_image));
Finally, here is my Firebase Database:
Careless mistake:
private static final String POLL_LABEL = "Poll";
Should be:
private static final String POLL_LABEL = "Polls";
The first choice was not the correct Firebase referencing thus causing the error.
Related
I'm trying to make a replica chat app and I have a list that I need populated into the recyclerview. I'm getting data from firebase realtime database and every time I receive or actually send a message, All the previous item(messages) plus the new one are repopulated/duplicated into the recycler view.
What I have tried
I have tried using .cleaar() method on my list before adding a new item to the list but now all other items in the recycler view disappear
here's my adapter
public class MessageAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
public static final int MSG_TYPE_LEFT = 0;
public static final int MSG_TYPE_RIGHT = 1;
FirebaseUser firebaseUser;
private Context ctx;
private List<Messages> msgsR, msgsS;//ignore unused
private ArrayList<Messages> dataSet;
public MessageAdapter(Context context) {
this.ctx = context;
this.dataSet = new ArrayList<>();
//this.msgsR = messagesReceived;
}
#Override
public RecyclerView.ViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
if (viewType == Messages.SENT_TYPE) {
View view = LayoutInflater.from(ctx).inflate(R.layout.message_item_right, parent, false);
return new ViewHolderS(view);
}
if (viewType == Messages.RECEIVED_TYPE) {
View view = LayoutInflater.from(ctx).inflate(R.layout.message_item_left, parent, false);
return new ViewHolderR(view);
}
return null;
}
#Override
public void onBindViewHolder(#NonNull RecyclerView.ViewHolder holder, int position) {
Messages object = dataSet.get(position);
if (object != null) {
switch (object.type) {
case Messages.RECEIVED_TYPE:
((ViewHolderR) holder).populate(object, position);
break;
case Messages.SENT_TYPE:
((ViewHolderS) holder).populate(object, position);
break;
}
}
}
//recceives messages object to populate into list
//it does not matter where i put the .clear() method, after or below dataset.add() its still undesireable
public void addMessageSent(Messages messages){
dataSet.clear();
dataSet.add(messages);
// notifyItemInserted(dataSet.size()-1);
//notifyItemRangeChanged(dataSet.size()-1, dataSet.size());
}
#Override
public int getItemCount() {
return dataSet.size();
}
// sent messages are handled here
public static class ViewHolderS extends RecyclerView.ViewHolder {
public TextView msg, time;
public LinearLayout layout;
public ViewHolderS(#NonNull View itemView) {
super(itemView);
layout = itemView.findViewById(R.id.cont);
msg = itemView.findViewById(R.id.send_msg);
time = itemView.findViewById(R.id.time);
}
private void populate(Messages messages, int position) {
msg.setText(messages.getMessage());
msg.setPadding(6, 4, 18, 4);
msg.setMinWidth(100);
msg.setMaxWidth(400);
LinearLayout.LayoutParams layoutParams = (LinearLayout.LayoutParams) msg.getLayoutParams();
layoutParams.gravity = Gravity.START;
layoutParams.width = LinearLayout.LayoutParams.WRAP_CONTENT;
layoutParams.height = LinearLayout.LayoutParams.WRAP_CONTENT;
layoutParams.topMargin = layoutParams.bottomMargin = layoutParams.rightMargin = 10;
layoutParams.leftMargin = 20;
msg.setLayoutParams(layoutParams);
time.setText(messages.getTime());
}
}
#Override
public int getItemViewType(int position) {
switch (dataSet.get(position).type) {
case 0:
return Messages.SENT_TYPE;
case 1:
return Messages.RECEIVED_TYPE;
default:
return -1;
}
}
// received messages are handled here
private class ViewHolderR extends ViewHolderS {
public TextView msg, time;
public LinearLayout layout;
public ViewHolderR(#NonNull View itemView) {
super(itemView);
layout = itemView.findViewById(R.id.cont);
msg = itemView.findViewById(R.id.send_msg);
time = itemView.findViewById(R.id.time);
}
private void populate(Messages messages, int position) {
msg.setText(messages.getMessage());
msg.setPadding(6, 4, 18, 4);
msg.setMinWidth(100);
msg.setMaxWidth(400);
LinearLayout.LayoutParams layoutParams = (LinearLayout.LayoutParams) msg.getLayoutParams();
layoutParams.gravity = Gravity.START;
layoutParams.width = LinearLayout.LayoutParams.WRAP_CONTENT;
layoutParams.height = LinearLayout.LayoutParams.WRAP_CONTENT;
layoutParams.topMargin = layoutParams.bottomMargin = layoutParams.rightMargin = 10;
layoutParams.leftMargin = 20;
msg.setLayoutParams(layoutParams);
time.setText(messages.getTime());
}
}
}
and here's my data model
public class Messages {
private String message;
public static final int SENT_TYPE=0;
public static final int RECEIVED_TYPE=1;
public static final int AUDIO_TYPE=2;
private long time;
public int type;
private String id;
private String receiver;
public Messages(String message,long time, String sender,String receiver, int type) {
this.message = message;
this.time = time;
this.id = sender;
this.type = type;
this.receiver = receiver;
}
public Messages() {
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
public String getTime() {
SimpleDateFormat output = new SimpleDateFormat("HH:mm", Locale.getDefault());
return output.format(new Date(time));
}
public void setTime(long time) {
this.time = time;
}
public String getSender() {
return id;
}
public void setSender(String sender) {
this.id = sender;
}
public String getReceiver() {
return receiver;
}
public void setReceiver(String receiver) {
this.receiver = receiver;
}
}
and below is activity class where I set the adapter and fill the list
recyclerView.setHasFixedSize(true);
LinearLayoutManager linearLayoutManager = new LinearLayoutManager(getApplicationContext());
linearLayoutManager.setStackFromEnd(true);
recyclerView.setLayoutManager(linearLayoutManager);
list= new ArrayList();
messageAdapter = new MessageAdapter(PersonChatActivity.this);
recyclerView.setAdapter(messageAdapter);
recyclerView.setItemAnimator(new DefaultItemAnimator());
if (Objects.requireNonNull(recyclerView.getAdapter()).getItemCount() > 0) {
recyclerView.smoothScrollToPosition(recyclerView.getAdapter().getItemCount());
}
//get sent messages from firebase
private void getmessages() {
DatabaseReference reference = database.getReference("Chats");
reference.keepSynced(true);
reference.child(senderId).child(receiver).push();
reference.child(senderId).child(receiver).addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
messageSent.clear();
for (DataSnapshot dataSnapshot : snapshot.getChildren()) {
if (dataSnapshot.getValue() != null) {
String message = (String) dataSnapshot.child("message").getValue();
long time = (Long) dataSnapshot.child("time").getValue();
String senderId = (String) dataSnapshot.child("id").getValue();
String receiverId = (String) dataSnapshot.child("receiver").getValue();
assert firebaseUser != null;
String user = firebaseUser.getUid();
Messages msg = new Messages(message, time, senderId, receiverId,Messages.SENT_TYPE);
String Uid = msg.getSender();
if (!Uid.isEmpty() && Uid.equals(user)) {
//pass the new message object to messages adapter to fill the list
messageAdapter.addMessageSent(msg);
}
}
}
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
}
});
}
EDIT UPDATE
As suggested I have made the necessary changes and code works like magic
I wont update the right changes into the question in case someone makes the same mistake as I have plus the comment marked as answer basically highlights the correct changes,,
NEW PROBLEM
The new problem is, on adding object message to the addMessagesent() previously populated recyclerview items get replaced by the new data.
to make it easy, on receiving a new message, all the previous visible sent messagees disappear and are replaced by the new received messages
here is my getmessageReceived() method
DatabaseReference reference = database.getReference("Chats");
reference.keepSynced(true);
reference.child(receiver).child(senderId).push();
reference.child(receiver).child(senderId).addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
messageReceived.clear();
messageAdapter.clearAllMessage();
for (DataSnapshot dataSnapshot : snapshot.getChildren()) {
if (dataSnapshot.getValue() != null) {
String message = (String) dataSnapshot.child("message").getValue();
long time = (Long) dataSnapshot.child("time").getValue();
String senderId = (String) dataSnapshot.child("id").getValue();
String receiverId = (String) dataSnapshot.child("receiver").getValue();
assert firebaseUser != null;
String user = firebaseUser.getUid();
Messages msg = new Messages(message, time, senderId, receiverId,Messages.RECEIVED_TYPE);
String Uid = msg.getReceiver();
if (!Uid.isEmpty() && Uid.equals(user)) {
messageAdapter.addMessageSent(msg);
messageAdapter.notifyDataSetChanged();
}
}
}
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
}
});
}
You should not clear the data set in the addMessageSent() just add new item to data set as shown below
public void addMessageSent(Messages messages){
dataSet.add(messages);
}
and create a new method to clear the dataset in your adapter
public void clearAllMessage(){
dataSet.clear();
}
And in getmessages() call clearAllMessage() like this
private void getmessages() {
DatabaseReference reference = database.getReference("Chats");
reference.keepSynced(true);
reference.child(senderId).child(receiver).push();
reference.child(senderId).child(receiver).addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
messageSent.clear();
clearAllMessage();
for (DataSnapshot dataSnapshot : snapshot.getChildren()) {
if (dataSnapshot.getValue() != null) {
String message = (String) dataSnapshot.child("message").getValue();
long time = (Long) dataSnapshot.child("time").getValue();
String senderId = (String) dataSnapshot.child("id").getValue();
String receiverId = (String) dataSnapshot.child("receiver").getValue();
assert firebaseUser != null;
String user = firebaseUser.getUid();
Messages msg = new Messages(message, time, senderId, receiverId,Messages.SENT_TYPE);
String Uid = msg.getSender();
if (!Uid.isEmpty() && Uid.equals(user)) {
//pass the new message object to messages adapter to fill the list
messageAdapter.addMessageSent(msg);
messageAdapter.notifyDataSetChanged(); // Call this also
}
}
}
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
}
});
}
I am developing an android app which shows a list of countries affected by Coronavirus , the total number of confirmed cases and total Deaths. I am using a JSON API to get the data and displaying it using a RecyclerView . The app works fine , and i get a list of all the countries with their respective case counts. I want to add a search option so that the users can filter the list and find a specific country. How do i do that? I am new to programming , if someone could help with this that would be awesome.
Here is the code snippet
MainActivity.java
private RecyclerView mRecyclerView;
private Corona_Stats_Adapter mCorona_Stats_Adapter;
private TextView mErrorDisplay;
private ProgressBar mProgressBar;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.corona_stats);
mRecyclerView = (RecyclerView)findViewById(R.id.Corona_stats_recycler);
mErrorDisplay = (TextView) findViewById(R.id.tv_error_message_display);
LinearLayoutManager layoutManager = new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false);
mRecyclerView.setLayoutManager(layoutManager);
mRecyclerView.setHasFixedSize(true);
mCorona_Stats_Adapter = new Corona_Stats_Adapter();
mRecyclerView.setAdapter(mCorona_Stats_Adapter);
mProgressBar = (ProgressBar)findViewById(R.id.pb_loading_indicator) ;
loadCoronaData();
}
private void loadCoronaData(){
showCoronaDataView();
//String Country = String.valueOf(mSearchQuery.getText());
new Fetch_data().execute();
}
private void showCoronaDataView(){
mErrorDisplay.setVisibility(View.INVISIBLE);
mRecyclerView.setVisibility(View.VISIBLE);
}
private void showErrorMessage(){
mRecyclerView.setVisibility(View.INVISIBLE);
mErrorDisplay.setVisibility(View.VISIBLE);
}
public class Fetch_data extends AsyncTask<Void,Void,String[]> {
#Override
protected void onPreExecute() {
super.onPreExecute();
mProgressBar.setVisibility(View.VISIBLE);
}
#Override
protected String[] doInBackground(Void... voids) {
URL covidRequestURL = NetworkUtils.buildUrl();
try {
String JSONCovidResponse = NetworkUtils.getResponseFromHttpUrl(covidRequestURL);
String[] simpleJsonCovidData = CovidJSON_Utils.getSimpleStringFromJson(MainActivity.this, JSONCovidResponse);
return simpleJsonCovidData;
} catch (IOException | JSONException e) {
e.printStackTrace();
return null;
}
}
#Override
protected void onPostExecute(String[] coronaData) {
mProgressBar.setVisibility(View.INVISIBLE);
if(coronaData !=null){
showCoronaDataView();
mCorona_Stats_Adapter.setCoronaData(coronaData);
} else{
showErrorMessage();
}
}
}
}
RecyclerView Adapter class Corona_stats_Adapter.java
public class Corona_Stats_Adapter extends RecyclerView.Adapter<Corona_Stats_Adapter.Corona_Stats_AdapterViewHolder>
{
private Context context;
// private List<Country> countryList;
// private List<Country> countryListFiltered;
private String[] mCoronaData;
public Corona_Stats_Adapter(){
}
#NonNull
#Override
public Corona_Stats_AdapterViewHolder onCreateViewHolder(#NonNull ViewGroup viewGroup, int viewType) {
Context context = viewGroup.getContext();
int LayoutIdForListItem =R.layout.corona_stats_list_item;
LayoutInflater inflater =LayoutInflater.from(context);
boolean ShouldAttachToParentImmediately = false;
View view = inflater.inflate(LayoutIdForListItem,viewGroup,ShouldAttachToParentImmediately);
return new Corona_Stats_AdapterViewHolder(view);
}
#Override
public void onBindViewHolder(#NonNull Corona_Stats_AdapterViewHolder corona_stats_adapterViewHolder, int position) {
String coronaStats = mCoronaData[position];
corona_stats_adapterViewHolder.mCoronaTextView.setText(coronaStats);
}
#Override
public int getItemCount() {
if(null == mCoronaData) return 0;
return mCoronaData.length;
// return countryListFiltered.size();
}
public class Corona_Stats_AdapterViewHolder extends RecyclerView.ViewHolder {
public final TextView mCoronaTextView;
public Corona_Stats_AdapterViewHolder(#NonNull View view) {
super(view);
mCoronaTextView = (TextView) view.findViewById(R.id.tv_corona_data);
}
}
public void setCoronaData(String[] coronaData){
mCoronaData = coronaData;
notifyDataSetChanged();
}
}
Parsing the JSON data in CovidJSON_Utils.java
public final class CovidJSON_Utils {
public static String[] getSimpleStringFromJson(Context context, String codivJsonString)
throws JSONException {
final String COV_COUNTRY = "Countries";
final String COV_CONFIRMED = "confirmed";
final String COV_DEATHS = "deaths";
final String COV_MESSAGE_CODE = "code";
String[] parsedCovidData = null;
JSONObject covidJsonObject = new JSONObject(codivJsonString);
if (covidJsonObject.has(COV_MESSAGE_CODE)) {
int errorCode = covidJsonObject.getInt(COV_MESSAGE_CODE);
switch (errorCode) {
case HttpURLConnection.HTTP_OK:
break;
case HttpURLConnection.HTTP_NOT_FOUND:
return null;
default:
return null;
}
}
JSONArray countryCovidArray = covidJsonObject.getJSONArray(COV_COUNTRY);
parsedCovidData = new String[countryCovidArray.length()];
for (int i = 0; i < countryCovidArray.length(); i++) {
JSONObject countryJSONObject = countryCovidArray.getJSONObject(i);
String Country = countryJSONObject.getString("Country");
String Confirmed = String.valueOf(countryJSONObject.getInt("TotalConfirmed"));
String Deaths = String.valueOf(countryJSONObject.getInt("TotalDeaths"));
parsedCovidData[i] = Country + "- Cases " + Confirmed + "- Deaths " + Deaths;
}
return parsedCovidData;
}
}
The problem is with below initialization in the MainActivity.Oncreate method
mCorona_Stats_Adapter = new Corona_Stats_Adapter(this,countries);
Initialize the adapter in onPostExecute method with updated countries data.
Hope this will help you.
You have to set arraylist to update country data in adapter after getting data from the server.
Public void setCoronaData (Arraylist coronaData) {
countryList = coronaData;
notifyDataSetChanged ();
}
im trying to update books on firebase but whenever i click update a new table is created
this is the search page
AdminSearch.java
public class AdminSearch extends AppCompatActivity {
EditText searchbarr;
RecyclerView recyclerVieww;
DatabaseReference referencee;
ArrayList<String> BookNameLists;
ArrayList<String> AuthorNameLists;
ArrayList<String> PicLists;
ArrayList<String> PublisherLists;
ArrayList<String> LinkLists;
ArrayList<String> DescriptionLists;
ArrayList<String>UidList;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_adminsearch);
searchbarr = (EditText) findViewById(R.id.searchbar);
referencee = FirebaseDatabase.getInstance().getReference();
referencee.keepSynced(true);
recyclerVieww = (RecyclerView) findViewById(R.id.rv);
recyclerVieww.setHasFixedSize(true);
recyclerVieww.setLayoutManager(new LinearLayoutManager(this));
recyclerVieww.addItemDecoration(new DividerItemDecoration(this, LinearLayoutManager.VERTICAL));
BookNameLists = new ArrayList<>();
PublisherLists = new ArrayList<>();
AuthorNameLists = new ArrayList<>();
LinkLists = new ArrayList<>();
PicLists = new ArrayList<>();
DescriptionLists=new ArrayList<>();
UidList=new ArrayList<>();
searchbarr.addTextChangedListener(new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
#Override
public void afterTextChanged(Editable s) {
if (!s.toString().isEmpty()) {
setAdapter(s.toString());
}
else{
BookNameLists.clear();
AuthorNameLists.clear();
PicLists.clear();
PublisherLists.clear();
DescriptionLists.clear();
UidList.clear();
}
}
private void setAdapter(final String searchedString) {
referencee.child("books").addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
BookNameLists.clear();
AuthorNameLists.clear();
PicLists.clear();
PublisherLists.clear();
DescriptionLists.clear();
UidList.clear();
int counter=0;
for(DataSnapshot snapshot:dataSnapshot.getChildren()){
String uid = snapshot.getKey();
String desc = snapshot.child("Desc").getValue(String.class);
String bookname = snapshot.child("bookname").getValue(String.class);
String author = snapshot.child("author").getValue(String.class);
String image = snapshot.child("image").getValue(String.class);
String publisher = snapshot.child("Publisher").getValue(String.class);
String link=snapshot.child("link").getValue(String.class);
String decscription=snapshot.child("Desc").getValue(String.class);
try {
if ((bookname.toLowerCase().contains(searchedString.toLowerCase())) || (author.toLowerCase().contains(searchedString.toLowerCase()))) {
UidList.add(uid);
BookNameLists.add(bookname);
AuthorNameLists.add(author);
PublisherLists.add(publisher);
PicLists.add(image);
DescriptionLists.add(decscription);
LinkLists.add(link);
counter++;
}
if(BookNameLists.isEmpty() && AuthorNameLists.isEmpty()){
Toast.makeText(getApplicationContext(),"not found",Toast.LENGTH_LONG).show();
}
}
catch (Exception e){
}
if(counter==15){
break;
}
AdminSearchAdapter adminSearchAdapter = new AdminSearchAdapter(AdminSearch.this, BookNameLists, AuthorNameLists, PicLists, PublisherLists,DescriptionLists,LinkLists,UidList);
recyclerVieww.setAdapter(adminSearchAdapter);
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
});
}
the adapter class for the search page
AdminSearchAdapter.java
public class AdminSearchAdapter extends RecyclerView.Adapter<AdminSearchAdapter.EditViewHolder> {
Context c;
ArrayList<String> BookNameLists;
ArrayList<String> AuthorNameLists;
ArrayList<String> PicLists;
ArrayList<String> PublisherLists;
ArrayList<String>DescriptionLists;
ArrayList<String>LinkLists;
LinearLayout booklayoutt;
ArrayList<String>UidList;
FirebaseDatabase db;
DatabaseReference referencee;
public String key;
class EditViewHolder extends RecyclerView.ViewHolder{
ImageView bookimages;
TextView booknamess, authornamess,publisherss;
public EditViewHolder(#NonNull View itemView) {
super(itemView);
bookimages = itemView.findViewById(R.id.Bookimg);
booknamess = itemView.findViewById(R.id.BookName);
authornamess = itemView.findViewById(R.id.AuthorName);
publisherss = itemView.findViewById(R.id.Publications);
booklayoutt=itemView.findViewById(R.id.LinLayout);
referencee = FirebaseDatabase.getInstance().getReference();
referencee.keepSynced(true);
}
}
public AdminSearchAdapter(Context c1, ArrayList<String> bookNameLists, ArrayList<String> authorNameLists, ArrayList<String> picLists, ArrayList<String> publisherLists, ArrayList<String> descriptionLists, ArrayList<String> linkLists,ArrayList<String> uidList) {
c = c1;
BookNameLists = bookNameLists;
AuthorNameLists = authorNameLists;
PicLists = picLists;
PublisherLists=publisherLists;
DescriptionLists=descriptionLists;
LinkLists=linkLists;
UidList=uidList;
}
#NonNull
#Override
public AdminSearchAdapter.EditViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(c).inflate(R.layout.activity_search_layout,parent,false);
return new AdminSearchAdapter.EditViewHolder(view);
}
#Override
public void onBindViewHolder(#NonNull final EditViewHolder holder, final int position) {
holder.booknamess.setText(BookNameLists.get(position));
holder.authornamess.setText(AuthorNameLists.get(position));
holder.publisherss.setText(PublisherLists.get(position));
holder.itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent i = new Intent(c, AdminBookdetails.class);
i.putExtra("uid",UidList.get(position));
i.putExtra("booknamess",BookNameLists.get(position));
i.putExtra("Images",PicLists.get(position));
i.putExtra("author_names",AuthorNameLists.get(position));
i.putExtra("publisher_names",PublisherLists.get(position));
i.putExtra("descriptions",DescriptionLists.get(position));
i.putExtra("links",LinkLists.get(position));
c.startActivity(i);
}
});
Glide.with(c).asBitmap().load(PicLists.get(position)).placeholder(R.mipmap.ic_launcher_round).into(holder.bookimages);
}
#Override
public int getItemCount() {
return BookNameLists.size();
}
this is the book details layout page where onlick the specific books details are sent and where i want to update it
AdminBookdetails.java
public class AdminBookdetails extends AdminSearch {
EditText titles,authors,pubs,linkss,descss,bookid;
Bookdeets bookdeets;
String key;
Button update;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_adminbooksdetails);
titles = (EditText) findViewById(R.id.bknames);
authors = (EditText) findViewById(R.id.anames);
pubs = (EditText) findViewById(R.id.pnames);
linkss = (EditText) findViewById(R.id.bklinks);
descss = (EditText) findViewById(R.id.bkdescriptions);
update=(Button)findViewById(R.id.updatebtn);
bookid=(EditText)findViewById(R.id.uid);
bookdeets=new Bookdeets();
final DatabaseReference databaseReference=FirebaseDatabase.getInstance().getReference().child("books");
String uid = getIntent().getStringExtra("uid");
bookid.setText(uid,TextView.BufferType.EDITABLE);
String Bname = getIntent().getStringExtra("booknamess");
titles.setText(Bname,TextView.BufferType.EDITABLE);
String Author = getIntent().getStringExtra("author_names");
authors.setText(Author,TextView.BufferType.EDITABLE);
String publisher = getIntent().getStringExtra("publisher_names");
pubs.setText(publisher,TextView.BufferType.EDITABLE);
final String Link = getIntent().getStringExtra("links");
linkss.setText(Link,TextView.BufferType.EDITABLE);
String Desc = getIntent().getStringExtra("descriptions");
descss.setText(Desc);
descss.setMovementMethod(new ScrollingMovementMethod());
update.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String Title = titles.getText().toString().trim();
String Author = authors.getText().toString().trim();
String Publisher = pubs.getText().toString().trim();
String Link = linkss.getText().toString().trim();
String Desc = descss.getText().toString().trim();
String Uid=bookid.getText().toString().trim();
Toast.makeText(getApplicationContext(),""+Title,Toast.LENGTH_SHORT).show();
bookdeets.setBookname(titles.getText().toString().trim());
bookdeets.setAuthor(authors.getText().toString().trim());
bookdeets.setPublisher(pubs.getText().toString().trim());
bookdeets.setLink(linkss.getText().toString().trim());
bookdeets.setDesc(descss.getText().toString().trim());
bookdeets.setId(bookid.getText().toString().trim());
databaseReference.push().setValue(bookdeets);
if(TextUtils.isEmpty(Title) ||TextUtils.isEmpty(Author)||TextUtils.isEmpty(Publisher)||TextUtils.isEmpty(Link)||TextUtils.isEmpty(Desc)){
titles.setError("Field cant be empty");
}
}
});
}
Use this code in AdminBookdetails.java
String Title = titles.getText().toString().trim();
String Author = authors.getText().toString().trim();
String Publisher = pubs.getText().toString().trim();
String Link = linkss.getText().toString().trim();
String Desc = descss.getText().toString().trim();
String Uid=bookid.getText().toString().trim();
HashMap<String, Object> map = new HashMap<>();
map.put("bookName", Title);
map.put("author", Author);
map.put("publisher", Publisher);
map.put("link", Link);
map.put("desc", Desc);
map.put("id", Uid);
databaseReference.child(Uid).updateChildren(map); //To Update value
To update use
databaseReference.child(Uid).updateChildren(map);
To add use
databaseReference.child(Uid).setValue(map);
hello I am new to android in my app i have one ListFragment activity in which i am getting data perfectly where i have list of users now i want that after click on any user i need to show their profile
public class HomeFragment extends ListFragment {
//CustomAdapter adapter;
//private List<RowItem> rowItems;
private ProgressDialog pDialog;
//JSON parser class
JSONParser jsonParser = new JSONParser();
JSONArray matching=null;
ArrayList<HashMap<String,String>> aList;
private static String MATCH_URL = null;
private static final String TAG_MATCH="matching";
private static final String TAG_MATCH_ID="match_detail_id";
private static final String TAG_NAME="name";
private static final String TAG_PROFILE="profile_id";
private static final String TAG_IMAGE="image";
private static final String TAG_CAST="cast";
private static final String TAG_AGE="age";
private static final String TAG_LOCATION="location";
private ListView listview;
String user_match_id;
public HomeFragment(){}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
String strtext = getArguments().getString("user_login_id");
MATCH_URL = "http://abcd.com/webservice/matching?version=apps&user_login_id="+strtext;
View rootView = inflater.inflate(R.layout.fragment_home, container, false);
aList = new ArrayList<HashMap<String,String>>();
// rowItems = new ArrayList<RowItem>();
listview=(ListView)rootView.findViewById(android.R.id.list);
new LoadAlbums().execute();
return rootView;
}
class LoadAlbums extends AsyncTask<String, String, ArrayList<HashMap<String,String>>> {
/**
* Before starting background thread Show Progress Dialog
* */
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(getActivity());
pDialog.setMessage("Loading...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(false);
pDialog.show();
}
protected ArrayList<HashMap<String,String>> doInBackground(String... args) {
ServiceHandler sh = new ServiceHandler();
// Making a request to url and getting response
String jsonStr = sh.makeServiceCall(MATCH_URL, ServiceHandler.GET);
Log.d("Response: ", "> " + jsonStr);
ArrayList<HashMap<String,String>> listData = new ArrayList<HashMap<String, String>>();
if (jsonStr != null) {
try {
JSONObject jsonObj = new JSONObject(jsonStr);
// Getting JSON Array node
matching = jsonObj.getJSONArray(TAG_MATCH);
// looping through All Contacts
for (int i = 0; i < matching.length(); i++) {
JSONObject c = matching.getJSONObject(i);
// creating new HashMap
HashMap<String, String> map = new HashMap<String, String>();
// adding each child node to HashMap key => value
map.put(TAG_MATCH_ID, c.getString(TAG_MATCH_ID));
map.put(TAG_NAME,c.getString(TAG_NAME));
map.put(TAG_PROFILE, c.getString(TAG_PROFILE));
map.put(TAG_IMAGE, c.getString(TAG_IMAGE));
map.put(TAG_CAST, c.getString(TAG_CAST));
map.put(TAG_AGE, c.getString(TAG_AGE)+" years");
map.put(TAG_LOCATION, c.getString(TAG_LOCATION));
// adding HashList to ArrayList
listData.add(map);
}
} catch (JSONException e) {
e.printStackTrace();
}
} else {
Log.e("ServiceHandler", "Couldn't get any data from the url");
}
return listData;
}
protected void onPostExecute( ArrayList<HashMap<String,String>> result) {
super.onPostExecute(result);
// dismiss the dialog after getting all albums
if (pDialog.isShowing())
pDialog.dismiss();
// updating UI from Background Thread
/**
* Updating parsed JSON data into ListView
* */
listview.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
long arg3) {
// TODO Auto-generated method stub
Intent intent=new Intent(getActivity(),ProfileEdit.class);
intent.putExtra("match_detail_id", arg2);
startActivity(intent);
}
});
if(aList==null){
aList = new ArrayList<HashMap<String, String>>();
}
aList.addAll(result);
CustomAdapter adapter = new CustomAdapter(getActivity(),aList);
setListAdapter(adapter);
}
}
public class ProfilePage extends Activity{
private ProgressDialog pDialog;
AQuery androidAQuery=new AQuery(this);
//private static final String TAG_MATCH_ID="match_detail_id";
private static final String USER_NAME="name";
private static final String USER_AGE="age";
private static final String USER_LOCATION="location";
private static final String USER_MOTHER_TONGE="mother_tounge";
private static final String USER_OCCU="occupation";
private static final String USER_INCOM="income";
private static final String USER_HEIGHT="height";
private static final String USER_MARRAGE="marital_status";
private static final String USER_RELIGION="religion";
private static final String USER_GOTRA="gotra";
private static final String USER_MANGLIK="manglik";
private static final String USER_RASHI="rashi";
private static final String USER_EDUCATION="education";
private static final String USER_EAT="eating";
private static final String USER_DRINK="drink";
private static final String USER_SMOKE="smoke";
private static final String USER_ABOUT="about_me";
private static final String USER_PIC="profile_pic";
private static String USER_URL="";
String user_match_id;
private ImageView cover;
private ImageView yes;
private ImageView no;
private ImageView sendmsg;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.profile_page);
String matchId=this.getIntent().getStringExtra("match_detail_id");
if(matchId.trim().length()>0){
USER_URL="http://abcds.com/webservice/matchingdetails?version=apps&match_detail_id="+user_match_id;
}else{
Toast.makeText(ProfilePage.this,"match id blank",Toast.LENGTH_LONG).show();
}
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
ServiceHandler sh = new ServiceHandler();
// Making a request to url and getting response
String jsonStr = sh.makeServiceCall(USER_URL, ServiceHandler.GET);
Log.d("Response: ", "> " + jsonStr);
try {
JSONObject jsonObj = new JSONObject(jsonStr);
String user_name = jsonObj.getString(USER_NAME);
String user_age = jsonObj.getString(USER_AGE);
String user_location = jsonObj.getString(USER_LOCATION);
String user_mothertong = jsonObj.getString(USER_MOTHER_TONGE);
String user_occupation = jsonObj.getString(USER_OCCU);
String user_income = jsonObj.getString(USER_INCOM);
String user_height = jsonObj.getString(USER_HEIGHT);
String user_marg = jsonObj.getString(USER_MARRAGE);
String user_religion = jsonObj.getString(USER_RELIGION);
String user_gotra = jsonObj.getString(USER_GOTRA);
String user_manglik = jsonObj.getString(USER_MANGLIK);
String user_rashi = jsonObj.getString(USER_RASHI);
String user_education = jsonObj.getString(USER_EDUCATION);
String user_eat = jsonObj.getString(USER_EAT);
String user_drink = jsonObj.getString(USER_DRINK);
String user_smoke = jsonObj.getString(USER_SMOKE);
String user_about = jsonObj.getString(USER_ABOUT);
String user_pro = jsonObj.getString(USER_PIC);
final TextView uname = (TextView)findViewById(R.id.namedetail);
final TextView fdetail = (TextView)findViewById(R.id.firstdetail);
final TextView sdetail = (TextView)findViewById(R.id.seconddetail);
final TextView tdetail = (TextView)findViewById(R.id.thirddetail);
final TextView ocdetail=(TextView)findViewById(R.id.txtoccupationdetail);
final TextView incomedetail = (TextView)findViewById(R.id.incomedetaile);
final TextView uheight = (TextView)findViewById(R.id.txtheightprofile);
final TextView umrg = (TextView)findViewById(R.id.txtmrgprofile);
final TextView ureligion = (TextView)findViewById(R.id.prohindu);
final TextView ugotra = (TextView)findViewById(R.id.gothraa);
final TextView umanglik = (TextView)findViewById(R.id.usermanglik);
final TextView urashi = (TextView)findViewById(R.id.rashi);
final TextView udegree = (TextView)findViewById(R.id.userdegree);
final TextView ueat = (TextView)findViewById(R.id.txteatprofile);
final TextView udrink = (TextView)findViewById(R.id.txtdrinkprofile);
final TextView usmoke = (TextView)findViewById(R.id.txtsmokeprofile);
final TextView uabout = (TextView)findViewById(R.id.txtabouther);
final ImageView ucover = (ImageView)findViewById(R.id.coverimage);
uname.setText(user_name);
fdetail.setText(user_age+" years");
sdetail.setText(user_location);
tdetail.setText(user_mothertong);
ocdetail.setText(user_occupation);
incomedetail.setText(user_income);
uheight.setText(user_height);
umrg.setText(user_marg);
ureligion.setText(user_religion);
ugotra.setText(user_gotra);
umanglik.setText(user_manglik);
urashi.setText(user_rashi);
udegree.setText(user_education);
ueat.setText(user_eat);
udrink.setText(user_drink);
usmoke.setText(user_smoke);
uabout.setText(user_about);
androidAQuery.id(ucover).image(user_pro, true, true);
} catch (JSONException e) {
e.printStackTrace();
}
Try to override onListItemClick in fragment :
#Override
public void onListItemClick(ListView l, View v, int position, long id) {
Intent intent = new Intent(getActivity(), ProfilePage.class);
intent.putExtra("match_detail_id", aList.get(position).get(TAG_MATCH_ID));
startActivity(intent);
}
Instead of manual setOnItemClickListener to listview so no required this code :
listview=(ListView)rootView.findViewById(android.R.id.list);
listview.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,long arg3) {
Intent intent=new Intent(getActivity().getApplicationContext(),ProfileEdit.class);
intent.putExtra("position", arg2);
startActivity(intent);
}
});
Note : when you use ListFragment no need to find Listview and set item click as well as setAdapter manually,directly get all method ready like setAdapter() and onListItemClick.
Intent intent = new Intent(getBaseContext(), NewActivity.class);
intent.putExtra("KEY", Value);
startActivity(intent)
Try with below code:
listview.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
long arg3) {
// TODO Auto-generated method stub
Intent intent=new Intent(getActivity(),ProfileEdit.class);
intent.putExtra("match_detail_id", arg2);
startActivity(intent);
}
});
//get this data as below in ProfileEdit class
String matchId=this.getIntent().getStringExtra(""match_detail_id"");
if(matchId.trim().length()>0){
USER_URL="http://gujjumatch.com/webservice/matchingdetails?version=apps&match_detail_id="+user_match_id;
}else{
Toast.makeText(ProfileEdit.this,"match id blank",Toast.LENGTH_LONG).show();
}
I have a SQLite Database of Web site data (ftp address, username, password, port, homedir, url etc). I can add records to the table but can't seem to update them.
I created a SiteManager Activity that loads each row and creates a WebSite object from each row. The WebSite's properties are loaded into EditTexts. The person can edit the properties and than the Update button SHOULD update the table row but it doesn't. Logcat doesn't give any errors so I'm completely at a loss, not sure where to start.
public class SiteManager extends Activity {
private DBAdapter myDb;
private EditText siteManFTPAddress;
private EditText siteManFTPUsername;
private EditText siteManFTPPassword;
private EditText siteManFTPPort;
private EditText siteManURL;
private EditText siteManHome;
private ImageView favIcon;
public ListView site_list;
private Button openBtn;
private Button siteManUpdateBtn;
private int _rowId;
private String _name;
private String _remoteHomeDir;
private int _isLive;
private String _address;
private String _username;
private String _password;
private int _port;
private String _url;
private boolean _status = false;
private String siteFolder;
private List<WebSite> model = new ArrayList<WebSite>();
private ArrayAdapter<WebSite> adapter;
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
setContentView(R.layout.site_manager);
site_list = (ListView) findViewById(R.id.siteList);
adapter = new SiteAdapter(this, R.id.ftpsitename, R.layout.siterow,
model);
site_list.setAdapter(adapter);
addListeners();
openDb();
displayRecords();
}
public void addListeners() {
siteManFTPAddress = (EditText) findViewById(R.id.siteManFTPAdd);
siteManFTPUsername = (EditText) findViewById(R.id.siteManFTPUser);
siteManFTPPassword = (EditText) findViewById(R.id.siteManFTPPass);
siteManFTPPort = (EditText) findViewById(R.id.siteManFTPPort);
siteManURL = (EditText) findViewById(R.id.siteManURL);
siteManHome = (EditText) findViewById(R.id.siteManHome);
site_list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, final View view,
int position, long id) {
File rootDir = new File(Environment
.getExternalStorageDirectory() + "/My Webs");
final WebSite item = (WebSite) parent
.getItemAtPosition(position);
_name = item.getName();
siteFolder = rootDir.toString() + "/" + _name;
_remoteHomeDir = item.getHomeDir();
_isLive = item.isLive();
String tmpaddress = item.getAddress();
_address = tmpaddress;
siteManFTPAddress.setText(_address);
String tmpuser = item.getUsername();
_username = tmpuser;
siteManFTPUsername.setText(_username);
String tmppass = item.getPassword();
_password = tmppass;
siteManFTPPassword.setText(_password);
int tmpport = item.getPort();
_port = tmpport;
String portString = Integer.toString(tmpport);
siteManFTPPort.setText(portString);
String tmpURL = item.getUrl();
_url = tmpURL;
siteManURL.setText(_url);
String tmpHome = item.getHomeDir();
_remoteHomeDir = tmpHome;
siteManURL.setText(_remoteHomeDir);
}
});
openBtn = (Button) findViewById(R.id.openSiteBtn);
openBtn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Intent returnResult = new Intent();
returnResult.putExtra("siteopen", "siteopen");
returnResult.putExtra("sitename", _name);
returnResult.putExtra("sitehome", siteFolder);
returnResult.putExtra("sitelive", _isLive);
returnResult.putExtra("siteremotehome", _remoteHomeDir);
returnResult.putExtra("siteaddress", _address);
returnResult.putExtra("siteusername", _username);
returnResult.putExtra("sitepassword", _password);
returnResult.putExtra("siteport", _port);
returnResult.putExtra("url", _url);
setResult(2, returnResult);
finish();
}
});
siteManUpdateBtn = (Button)findViewById(R.id.siteManFTPUpdate);
siteManUpdateBtn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
_address = siteManFTPAddress.getText().toString();
_username = siteManFTPUsername.getText().toString();
_password = siteManFTPPassword.getText().toString();
String port = siteManFTPPort.getText().toString();
_port = Integer.parseInt(port);
Toast.makeText(SiteManager.this, "Update", Toast.LENGTH_LONG).show();
myDb.updateRow(_rowId, _name, _name, _isLive, _address, _username, _password, _port, _url);
model.clear();
adapter.notifyDataSetChanged();
displayRecords();
}
});
}
private void openDb() {
myDb = new DBAdapter(this);
myDb.open();
}
#Override
protected void onDestroy() {
// TODO Auto-generated method stub
super.onDestroy();
closeDb();
}
private void closeDb() {
myDb.close();
}
public void displayRecords() {
Cursor cursor = myDb.getAllRows();
displayRecordSet(cursor);
}
protected void displayRecordSet(Cursor c) {
if (c.moveToFirst()) {
do {
int rowId = c.getInt(c.getColumnIndex(DBAdapter.KEY_ROWID));
_rowId = c.getInt(rowId);
int keyNameIndex = c.getColumnIndex(DBAdapter.KEY_NAME);
_name = c.getString(keyNameIndex);
int keyHomeIndex = c.getColumnIndex(DBAdapter.KEY_HOME);
_remoteHomeDir = c.getString(keyHomeIndex);
int keyLiveIndex = c.getColumnIndex(DBAdapter.KEY_LIVE);
_isLive = c.getInt(keyLiveIndex);
int keyAddressIndex = c.getColumnIndex(DBAdapter.KEY_ADDRESS);
_address = c.getString(keyAddressIndex);
int keyUsernameIndex = c.getColumnIndex(DBAdapter.KEY_USERNAME);
_username = c.getString(keyUsernameIndex);
int keyPassIndex = c.getColumnIndex(DBAdapter.KEY_PASSWORD);
_password = c.getString(keyPassIndex);
int keyPortIndex = c.getColumnIndex(DBAdapter.KEY_PORT);
_port = c.getInt(keyPortIndex);
int keyUrlIndex = c.getColumnIndexOrThrow(DBAdapter.KEY_URL);
_url = c.getString(keyUrlIndex);
WebSite sitesFromDB = new WebSite(_rowId, _name, _remoteHomeDir,
_isLive, _address, _username, _password, _port, _url);
model.add(sitesFromDB);
adapter.notifyDataSetChanged();
if(adapter.isEmpty()){
}
} while (c.moveToNext());
}
c.close();
}
#Override
protected void onResume() {
// TODO Auto-generated method stub
super.onResume();
adapter.notifyDataSetChanged();
}
class SiteAdapter extends ArrayAdapter<WebSite> {
private final List<WebSite> objects;
private final Context context;
public SiteAdapter(Context context, int resource,
int textViewResourceId, List<WebSite> objects) {
super(context, R.id.sitename, R.layout.siterow, objects);
this.context = context;
this.objects = objects;
}
/** #return The number of items in the */
public int getCount() {
return objects.size();
}
public boolean areAllItemsSelectable() {
return false;
}
/** Use the array index as a unique id. */
public long getItemId(int position) {
return position;
}
public View getView(int position, View convertView, ViewGroup parent) {
LayoutInflater inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View rowView = inflater.inflate(R.layout.siterow, parent, false);
TextView textView = (TextView) rowView.findViewById(R.id.sitename);
textView.setText(objects.get(position).getName());
return (rowView);
}
}
DBAdapter.java
public boolean updateRow(long rowId, String name, String homedir,
int islive, String address, String username, String password,
int port, String url) {
String where = KEY_ROWID + "=" + rowId;
/*
* CHANGE 4:
*/
// TODO: Update data in the row with new fields.
// TODO: Also change the function's arguments to be what you need!
// Create row's data:
ContentValues newValues = new ContentValues();
newValues.put(KEY_NAME, name);
newValues.put(KEY_HOME, homedir);
newValues.put(KEY_LIVE, islive);
newValues.put(KEY_ADDRESS, address);
newValues.put(KEY_USERNAME, username);
newValues.put(KEY_PASSWORD, password);
newValues.put(KEY_PORT, port);
newValues.put(KEY_URL, url);
// newValues.put(KEY_PASSIVE, passive);
// Insert it into the database.
return db.update(DATABASE_TABLE, newValues, where, null) != 0;
}
The value _rowId is only ever set inside the displayRecordSet method where you iterate through the results from the database and set the _rowId:
int rowId = c.getInt(c.getColumnIndex(DBAdapter.KEY_ROWID));
_rowId = c.getInt(rowId);
This piece of code seems rather random to me. First you get the columnIndex for the rowId, next you get the index for this specific row and then you get the value of the column with index rowId and then set the _rowId field from this value.
I couldn't tell if the SQLite Database would be so nasty as to just return 0 if there isn't any value in the specified column, but that could definately be the problem.
So every time you get the _rowId set, it might just be set to 0 and when you try to update a row where rowId = 0 nothing happens, as no index in the database can be 0.
See the official documentation about getInt(columnIndex).
To diagnose issues like this, I usually add debug logs into the app. You can see these in your logcat. Log.d("tag", "there is something happening here: " + value);