I have problem in transferring data from activity to another activity - java

public class Memo extends AppCompatActivity {
DBHandler dbh;
Notes items;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_memo);
getSupportActionBar().hide();
try{
dbh = new DBHandler(this);
}
catch (Exception ex){
ex.printStackTrace();
}
display();
}
public void display( ){ //method to display all items in the database
List<Notes> books_list = dbh.getNotes(); ////here i get the list fromm the database
///// i used a custom adapter because i needed it
final myAdapter adapter = new myAdapter(this, books_list); ///creating adapter from
myadapter to link it with the list
ListView _note_ = findViewById(R.id.list_txt);
_note_.setAdapter(adapter);
_note_.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
items = (Notes) adapter.getItem(position);
String Note_content = items.getNote();
String title = items.getTitle();
String Date = items.getDate();
Intent i = new Intent(getApplicationContext() ,Note_content.class);
i.putExtra("Note ", Note_content);
i.putExtra("title", title);
i.putExtra("Date", Date);
startActivity(i);
}
});
i have a problem when I try to to get data( only Note) from this activity to another activity, other values(Date and Title) are working, I tried to use toString method in Notes class but it gives null for note
public class Note_content extends AppCompatActivity {
Notes item;
TextView txt_note ,txt_date , txt_title;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_note_content);
txt_title = findViewById(R.id.txt_ntitle);
txt_note = findViewById(R.id.txt_Nnote);
txt_date = findViewById(R.id.txt_Ndate);
Intent i = getIntent();
String note = i.getStringExtra("Note");
String title = i.getStringExtra("title");
String date = i.getStringExtra("Date");
item = new Notes(title,note,date);
txt_note.setText(item.getNote());
//txt_note.setText(note)
txt_date.setText(date);
txt_title.setText(title);
}
this is the second activit, it is not giving any errors but null instead of the note
and this Notes class
public class Notes {
private int id;
private String title;
private String note ;
private String date;
public Notes() {
}
public Notes(String title, String note, String date) {
this.title = title;
this.note = note;
this.date = date;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getNote() {
return note;
}
public void setNote(String note) {
this.note = note;
}
public String getDate() {
return date;
}
public void setDate(String date) {
this.date = date;
}
#Override
public String toString() {
return this.note+"\n"+title+"\n"+date;
}
}

i.putExtra("Note ", Note_content);
In the above code line, "Note " has an extra space at the end.

Related

Not able to retrieve data from firebase

I have created a simple android to send and receive data from firebase. But every time I open a new activity for the data to be shown, it comes out blank.
I have tried all sorts of previously answered similar questions.
private void send(){
String n = name.getText().toString();
String b = bg.getText().toString();
String d = dob.getText().toString();
String l = loc.getText().toString();
String i = id.getText().toString();
String m = mob.getText().toString();
if(TextUtils.isEmpty(n) || TextUtils.isEmpty(b) || TextUtils.isEmpty(d) || TextUtils.isEmpty(l) || TextUtils.isEmpty(i)
|| TextUtils.isEmpty(m)){
Toast.makeText(this, "Details incomplete!!", Toast.LENGTH_SHORT).show();
}
else{
String id = root.push().getKey();
Person person = new Person(b,d,i,l,m,n);
root.child(id).setValue(person);
}
}
package com.example.yashkrishan.directory;
/**
* Created by yashkrishan on 4/1/19.
*/
public class Person {
private String bg;
private String dob;
private String id;
private String loc;
private String mob;
private String name;
public Person(String bg, String dob, String id, String loc, String mob, String name) {
this.bg = bg;
this.dob = dob;
this.id = id;
this.loc = loc;
this.mob = mob;
this.name = name;
}
public Person(){}
public void setName(String name) {
this.name = name;
}
public void setLoc(String loc) {
this.loc = loc;
}
public void setMob(String mob) {
this.mob = mob;
}
public void setDob(String dob) {
this.dob = dob;
}
public void setBg(String bg) {
this.bg = bg;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public String getLoc() {
return loc;
}
public String getMob() {
return mob;
}
public String getDob() {
return dob;
}
public String getBg() {
return bg;
}
public String getId() {
return id;
}
}
DatabaseReference ref;
FirebaseDatabase database;
ListView listView;
ArrayList<Person> list;
ArrayAdapter<Person> adapter;
Person person;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main2);
person = new Person();
listView = (ListView)findViewById(R.id.listView);
database = FirebaseDatabase.getInstance();
ref = database.getReference("Person");
list = new ArrayList<>();
adapter = new ArrayAdapter<Person>(this,R.layout.info, list);
ref.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for(DataSnapshot ds: dataSnapshot.getChildren()){
person = ds.getValue(Person.class);
list.add(person);
}
listView.setAdapter(adapter);
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
I want to display list of the data stored in firebase database into a list view in different activity.

TodoList application android

Please I need your help .I'am trying to take the date from an activity and then put it in an array list then print it in an ListView .
The problem is the data that I should take it from "Adding Todo" is not showing in the ListView . it do take me to the List Activity but without showing the data .
This is How the app going to be "Adding todo"
And this is the ListView where the data should be in it
My code :-
MainActivity
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
listView = findViewById(R.id.list_view);
arrayList = new ArrayList<>();
todoAdapter = new TodoAdapter(this , arrayList);
listView.setAdapter(todoAdapter);
}
public void onClick(View view) {
Intent intent = new Intent();
intent.setClass(MainActivity.this, AddTodo.class);
startActivityForResult(intent, Intent_Constants.INTENT_REQUEST_CODE);
}
protected void onActivityResult(int reqCode ,int resultCode , Intent data ){
// here Iam trying to get the data from ADDING TO DO class
if(resultCode == Intent_Constants.INTENT_REQUEST_CODE){
titleText = data.getStringExtra(Intent_Constants.INTENT_TITLE);
priorityText = data.getStringExtra(Intent_Constants.INTENT_PRIORITY);
statusText = data.getStringExtra(Intent_Constants.INTENT_STATUES);
dateText = data.getStringExtra(Intent_Constants.INTENT_DATE);
timeText = data.getStringExtra(Intent_Constants.INTENT_TIME);
todoAdapter.todo.add(new Todo (titleText , statusText ,priorityText ,dateText ,timeText));
}
}
Intent_Constants
public class Intent_Constants {
public final static int INTENT_REQUEST_CODE = 1;
public final static int INTENT_RESULT_CODE = 1 ;
public final static String INTENT_TITLE = "Title";
public final static String INTENT_PRIORITY = "Priority";
public final static String INTENT_TIME = "Time";
public final static String INTENT_DATE = "Date";
public final static String INTENT_STATUES = "Statues";
}
AddTodo class
In this class I find the id then I converted to String
public void saveButton (View view){
Intent intent = new Intent();
intent.putExtra(Intent_Constants.INTENT_TITLE , title);
intent.putExtra(Intent_Constants.INTENT_DATE , date);
intent.putExtra(Intent_Constants.INTENT_TIME , time);
intent.putExtra(Intent_Constants.INTENT_PRIORITY , priority);
intent.putExtra(Intent_Constants.INTENT_STATUES , completed);
setResult(INTENT_RESULT_CODE, intent);
finish();
}
TodoAdapter class
ArrayList<Todo> todo ;
public TodoAdapter(#NonNull Context context, ArrayList<Todo> todo) {
super(context, R.layout.todo_list,todo);
this.todo = todo;
}
public static class ViewHolder {
TextView titleText;
TextView priorityText;
TextView dateText;
TextView timeText;
CheckBox statusBox;
ImageButton edit_image;
ImageButton open_image;
ImageButton delet_image;
}
#NonNull
#Override
public View getView(int position, #Nullable View convertView, #NonNull ViewGroup parent) {
ViewHolder holder = null;
LayoutInflater inflater = LayoutInflater.from(getContext()) ;
View customeView =inflater.inflate(R.layout.todo_list,parent ,false);
holder.titleText.setText(getItem(position).getTitle());
holder.priorityText.setText(getItem(position).getPriority());
holder.dateText.setText(getItem(position).getDate());
holder.timeText.setText(getItem(position).getTime());
holder.statusBox.setChecked(false);
holder.edit_image = customeView.findViewById(R.id.edit_imageView);
holder.open_image = customeView.findViewById(R.id.open_imageButton);
holder.delet_image = customeView.findViewById(R.id.delete_imageView);
holder.edit_image.setImageResource(R.drawable.ic_edit_black_24dp);
holder.open_image.setImageResource(R.drawable.ic_refresh_black_24dp);
holder.delet_image.setImageResource(R.drawable.ic_delete_black_24dp);
return customeView;
}
Todo class
public class Todo {
private String title ;
private String status ;
private String priority ;
private String date ;
private String time ;
public Todo() {
}
public Todo(String title, String status, String priority, String date, String time) {
this.title = title;
this.status = status;
this.priority = priority;
this.date = date;
this.time = time;
}
public String getTitle() {
return title;
}
public String getStatus() {
return status;
}
public String getPriority() {
return priority;
}
public String getDate() {
return date;
}
public String getTime() {
return time;
}
public void setTitle(String title) {
this.title = title;
}
public void setStatus(String status) {
this.status = status;
}
public void setPriority(String priority) {
this.priority = priority;
}
public void setDate(String date) {
this.date = date;
}
public void setTime(String time) {
this.time = time;
}
}
You can just set a new adapter, I know it isn't best way, but should do the work. Don't create new one, but nulify yours, and initialize it with new data.
#Noura change this
arrayList.add(new Todo(titleText , statusText ,priorityText ,dateText ,timeText));
to
todoAdapter.todo.add(new Todo(titleText , statusText ,priorityText ,dateText ,timeText));
todoAdapter.notifyDataSetChanged();
and at the constructor u need to update your code like below
ArrayList<Todo> todo ;
public TodoAdapter(#NonNull Context context, ArrayList<Todo> todo) {
this.todo = todo
super(context, R.layout.todo_list,todo);
}

Resource Not Found while converting int value of id to String using Retrofit

I am using Retrofit to fetch and display data to the screen. I want to search users by their id's. I made interface like this :
#GET("/posts/{id}")
Call<postmodel> getUsersModel(#Path("id") int id);
The problem is with DetailActivity line 52:
EndPointAccess access = APIClient.getRetrofit().create(EndPointAccess.class);
Call<postmodel> modelCall = access.getUsersModel(Integer.parseInt(_userinput));
Here is the Logcat report:
android.content.res.Resources$NotFoundException:
String resource ID #0x1
at
android.content.res.Resources.getText(Resources.java:351)
at
android.content.res.MiuiResources.getText(MiuiResources.java:97)
at
android.widget.TextView.setText(TextView.java:4562)
at com.example.sahil.typicode1.Activity.DetailActivity$2.onResponse(DetailActivity.java:60)
APIClient.java
public static final String BASE_URL = "https://jsonplaceholder.typicode.com";
private static Retrofit retrofit = null;
public static Retrofit getRetrofit()
{
if (retrofit == null)
{
retrofit = new Retrofit.Builder().baseUrl(BASE_URL)
.addConverterFactory(GsonConverterFactory
.create()).build();
}
return retrofit;
}
EndPointAccess.java (Interface)
#GET("/posts/{id}")
Call<postmodel> getUsersModel(#Path("id") int id);
MainActivity.java
EditText userid;
Button search;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
userid = (EditText) findViewById(R.id.etuserid);
search = (Button) findViewById(R.id.btnsearch);
search.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(MainActivity.this,DetailActivity.class);
intent.putExtra("STRING_I_NEED",userid.getText().toString());
startActivity(intent);
}
});
}
DetailActivity.java
TextView userid,usertitle,userbody;
Button viewall;
String _userinput;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_detail);
Intent intent = getIntent();
_userinput = intent.getStringExtra("STRING_I_NEED");
userid = (TextView) findViewById(R.id.textViewid);
usertitle = (TextView) findViewById(R.id.textViewtitle);
userbody = (TextView) findViewById(R.id.textViewbody);
viewall = (Button) findViewById(R.id.btnviewall);
viewall.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Toast.makeText(DetailActivity.this, "Done!", Toast.LENGTH_SHORT).show();
}
});
getinfo();
}
private void getinfo()
{
EndPointAccess access = APIClient.getRetrofit().create(EndPointAccess.class);
Call<postmodel> modelCall = access.getUsersModel(Integer.parseInt(_userinput));
modelCall.enqueue(new Callback<postmodel>() {
#Override
public void onResponse(Call<postmodel> call, Response<postmodel> response)
{
userid.setText(response.body().getId());
usertitle.setText(response.body().getTitle());
userbody.setText(response.body().getBody());
}
#Override
public void onFailure(Call<postmodel> call, Throwable t) {
Toast.makeText(DetailActivity.this, "Error!", Toast.LENGTH_SHORT).show();
}
});
}
postmodel.java (pojo class)
private int id;
private String title;
private String body;
public postmodel(int id, String title, String body) {
this.id = id;
this.title = title;
this.body = body;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getBody() {
return body;
}
public void setBody(String body) {
this.body = body;
}
You are trying to set an integer in the setText function which only accepts String values. Therefore it is giving this error.
Hence you need to convert it into a string using String.valueOf() function.
remove userid.setText(response.body().getId());
add userid.setText(String.valueOf(response.body().getId()));
SetText with integer parameter looks resource with that id : reference
So you should pass an string value to setText()
userid.setText(String.valueOf(response.body().getId()));
So, replacing this line in DetailActivity.java might help you fix the exception :)

How to implement Parcelable

Good day. I need to implement parcelable in Model class.Currently it is Serializable. for now only setdate and set title if thare If any one can help. please edit code.
MainActivity.java
Document document = Jsoup.connect("http://feeds.bbci.co.uk/urdu/rss.xml").ignoreHttpErrors(true).get();
Elements itemElements = document.getElementsByTag("item");
for (int i = 0; i < itemElements.size(); i++) {
Element item = itemElements.get(i);
NewsItem newsItem = new NewsItem();
newsItem.setDate(item.child(4).text());
newsItem.setTitle(item.child(0).text());
newsItemsList.add(newsItem);
}
} catch (IOException e) {
e.printStackTrace();
}
runOnUiThread(new Runnable() {
#Override
public void run() {
adapter = new NewsAdaptor(Main2Activity.this,
newsItemsList);
lvRss.setAdapter(adapter);
}
});
return null;
}
NewsItem.java //model class
public class NewsItem implements Serializable {
String imagePath;
String title;
String link;
String date;
public NewsItem () {
}
public String getImagePath () {
return imagePath;
}
public void setImagePath ( String imagePath ) {
this.imagePath = imagePath;
}
public String getTitle () {
return title;
}
public void setTitle ( String title ) {
this.title = title;
}
public String getLink () {
return link;
}
public void setLink ( String link ) {
this.link = link;
}
public String getDate () {
return date;
}
public void setDate ( String date ) {
this.date = date;
}
NewsAdapter.java
public class NewsAdaptor extends BaseAdapter {
private int textSize;
TextView tvtitle;
private int color;
Context context;
public NewsAdaptor ( Context context, ArrayList <NewsItem> newsList ) {
this.context = context;
this.newsList = newsList;
this.color = Color.RED;
}
ArrayList<NewsItem> newsList;
#Override
public int getCount () {
return newsList.size();
}
#Override
public Object getItem ( int position ) {
return newsList.get(position);
}
#Override
public long getItemId ( int position ) {
return 0;
}
#Override
public View getView ( int position, View convertView, ViewGroup parent ) {
if (convertView == null){
convertView=View.inflate(context, R.layout.newsitemlist_layout,null);
}
NewsItem currentNews = newsList.get(position);
ImageView iv1 = (ImageView) convertView.findViewById(R.id.mainimg);
TextView tvdate = (TextView) convertView.findViewById(R.id.pubDateid);
Picasso.with(context).load(currentNews.getImagePath()).placeholder(R.drawable.expressimg).into(iv1);
tvdate.setText(currentNews.getDate());
tvtitle = (TextView) convertView.findViewById(R.id.textView1id);
tvtitle.setText(currentNews.getTitle());
tvtitle.setTextColor(color);
return convertView;
}
public void setTextColor(int color) {
this.color = color;
}
Check this Parcelable NewsItem:
public class NewsItem implements Parcelable {
String imagePath;
String title;
String link;
String date;
public NewsItem() {
}
protected NewsItem(Parcel in) {
imagePath = in.readString();
title = in.readString();
link = in.readString();
date = in.readString();
}
#Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeString(imagePath);
dest.writeString(title);
dest.writeString(link);
dest.writeString(date);
}
#Override
public int describeContents() {
return 0;
}
public static final Creator<NewsItem> CREATOR = new Creator<NewsItem>() {
#Override
public NewsItem createFromParcel(Parcel in) {
return new NewsItem(in);
}
#Override
public NewsItem[] newArray(int size) {
return new NewsItem[size];
}
};
public String getImagePath() {
return imagePath;
}
public void setImagePath(String imagePath) {
this.imagePath = imagePath;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getLink() {
return link;
}
public void setLink(String link) {
this.link = link;
}
public String getDate() {
return date;
}
public void setDate(String date) {
this.date = date;
}
}

Android intent bundle pass string

i have json to serializable claas then i use it to populate listview, and everything works fine but i want to populate textview on another xml page with one of the serializable object and i read to best way to do it is bundle intent, but i did code something wrong.
public class FeedItem implements Serializable {
private String title;
private String date;
private String attachmentUrl;
private String id;
private String content;
private String url;
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
public String getContent() {
return content;
}
public void setContent(String content) {
this.content = content;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getDate() {
return date;
}
public void setDate(String date) {
this.date = date;
}
public String getAttachmentUrl() {
return attachmentUrl;
}
public void setAttachmentUrl(String attachmentUrl) {
this.attachmentUrl = attachmentUrl;
}
#Override
public String toString() {
return "[ title=" + title + ", date=" + date + "]";
}
ArrayList<FeedItem> all_thumbs = new ArrayList<FeedItem>();
all_thumbs.add(new FeedItem(title);
Intent intent = new Intent(title);
Bundle extras = new Bundle();
extras.putSerializable("title",title);
intent.putExtras(extras);
}
and in the class where i want to use it
public void updateList() {
TextView infoz = (TextView) getView().findViewById(R.id.infoz);
Bundle args;
getArguments().getSerializable(title);
Instead use:
public void updateList() {
TextView infoz = (TextView) getView().findViewById(R.id.infoz);
Intent intent = getIntent();
Bundle extras = intent.getExtras();
String title = (String) extras.getSerializable("title");
IF you want to pass any primitive datatyped values (String,int,long,float etc.) then do not need to use Bundle.putExtra(KEY,Serialized Object) and Bundle.getSerializable(KEY). You can use Bundle.putExtra(KEY,primitive data);
If you want to pass class object to intent/bundle then you need to implement Serializable/Parsable in that class like:
public class Test implements Serializable
{
private static final long serialVersionUID = 1L;
int test1;
}
and then you can pass that object instance to intent like:
myIntent.putExtra( KEY, new Test() );
For more clarification check pass seriable object in intent example

Categories