I have a question what is the best, easiest, shortest way to create custom(personal listener to value, I mean if I had some if statement that's will triggers when some boolean variable will changed.
The problem is the welcomeName initialize as null, so I need few milli seconds before I set a text.
So I want exectue a listener, that will do this when the welcomeName will not be null.
Thanks.
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_trinee);
findViewById(R.id.trainee_home);
findViewById(R.id.trainee_training);
findViewById(R.id.trainee_cancel);
setFragmentLayout();
String nameLast="";
Bundle bundle = getIntent().getExtras();
welcomeName = (TextView) findViewById(R.id.username_string);
nameLast = bundle.getBundle("personalBundle").getString("name")+
" "+bundle.getBundle("personalBundle").getString("last");
if(welcomeName!=null)
{
welcomeName.setText(nameLast);
}
}
If all should run on the Main/UiThread, then the best way is using LiveData.
LiveData<Integer> mLiveData = new MutableLiveData<>();
void onCreate(Bundle savedInstance) {
mLiveData.observe(this, new Observer<Integer>() {
#Override
public void onChange(Integer value) {
//"value" is the last value of "variable" you want to observe
}
});
}
then from anywhere in the same Activity/Fragment:
mLiveData.postValue(1);
....
mLiveData.postValue(2);
....
button.setOnClickListener(new ... {
void onClick(View v) {
mLiveData.postValue(3);
}
});
Not so working.. I will very thanksful if you can give me some example how do I need implement it
LiveData<String> mLiveData = new MutableLiveData<>();
String nameLast = "";
TextView welcomeName;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Bundle bundle = getIntent().getExtras();
welcomeName = (TextView) findViewById(R.id.username_string);
nameLast = bundle.getBundle("personalBundle").getString("name") +
" " + bundle.getBundle("personalBundle").getString("last");
mLiveData.observe(this, new Observer<String>() {
#Override
public void onChanged(String str) {
welcomeName.setText(str);
}
});
Related
i have an activity that get a variable from another activity, and i want to display this variable when user click on button.
the problem is SaveFile(View view) method cannot find "SurveyTilte" variable.
How can i pass this variable?
public class CreateSurvey extends AppCompatActivity {
TextView Textfile;
String SurveyTilte;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.create_survey);
Bundle extras = getIntent().getExtras();
SurveyTilte = extras.getString("SurveyTilte");
}
}
i can't, but the code in OnClickListener because there is an #Override method
public void SaveFile(View view) {
Textfile = (TextView) findViewById(R.id.surveyDetails);
Textfile.setText(SurveyTilte);
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
switch (requestCode) {
case PERMISSION_REQUEST:
if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
Toast.makeText(CreateSurvey.this, "Permission granted", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(CreateSurvey.this, "Permission not granted", Toast.LENGTH_SHORT).show();
finish();
}
}
This is actually more a matter of java than android.
By doing:
protected void onCreate(Bundle savedInstanceState) {
...
String SurveyTilte = extras.getString("SurveyTilte");
}
What you actually do is creating a local variable separated from your class field variable with the same name, and is 'alive' and available for that specific method scope. Meaning you'll loose its reference (and thus its value) when exiting onCreate method.
What you need to do:
All you need to do is not to declare a new variable inside onCreate but to use the same variable you declared in advanced in your class attributes.
#Override
protected void onCreate(Bundle savedInstanceState) {
...
SurveyTilte = extras.getString("SurveyTilte");
}
That's how you can use the same reference for your value in the entire class scope.
Remove String keyword from String SurveyTilte = extras.getString("SurveyTilte"); to assign value to the class field and not local variable:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.create_survey);
Bundle extras = getIntent().getExtras();
SurveyTilte = extras.getString("SurveyTilte");
}
and then
public void SaveFile(View view) {
Textfile = (TextView) findViewById(R.id.surveyDetails);
Textfile.setText(SurveyTilte); // <-- reference field that contains value from intent data
}
I think this can help you.
public class CreateSurvey extends AppCompatActivity {
TextView Textfile;
String SurveyTilte;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.create_survey);
}
}
public void SaveFile(View view) {
Bundle extras = getIntent().getExtras();
if(extras != null) {
SurveyTilte = extras.getString("SurveyTilte");
Textfile = (TextView) findViewById(R.id.surveyDetails);
Textfile.setText(SurveyTilte);
}
}
Here is my situation.
In this screen, I click the comments button.
The Comment activity opens and I type what I want.
The comment is added successfully in firebase and it takes me back in detail activity.
So far everything is great! Now let's add another comment. Now you see I get duplicate comments.
I hope you see that too. Now in the DetailActivity I have a method called queryFirebaseDb() and that method is called inside both onCreate() and onResume() methods. If I don't use the onResume() method the data will not be display after clicking the back button from the CommentActivity. You see where I am going now right? The question is how to avoid duplicate data after coming back from CommentActivity. Here is my code.
public class DetailActivity extends AppCompatActivity {
ArrayList<Comment> commentArrayList;
ImageView mImageView;
TextView mTitle;
TextView mDate;
TextView mDescription;
TextView mAuthor;
ToggleButton mFavBtn;
private TextView noCommentsTextView;
private TextView commentsTextView;
private ImageButton imageButton;
private FloatingActionButton mShareBtn;
private String newsTitle;
private String newsImage;
private String newsDate;
private String newsDescription;
private static String NEWS_SHARE_HASHTAG = "#EasyNewsApp";
private String date1;
private String date2;
private String newsUrl;
private String newsAuthor;
private Cursor favoriteCursor;
private DatabaseReference mDatabase;
private static Bundle bundle = new Bundle();
private Uri uri;
private RecyclerView mRecyclerView;
private DisplayCommentsAdapter displayCommentsAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_detail);
Toolbar toolbar = (Toolbar) findViewById(R.id.detail_toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
Intent i = getIntent();
mAuthor = (TextView) findViewById(R.id.detail_author);
mImageView = (ImageView) findViewById(R.id.detail_image_view);
mTitle = (TextView) findViewById(R.id.detail_title);
mDate = (TextView) findViewById(R.id.detail_publish_date);
mDescription = (TextView) findViewById(R.id.detail_description);
noCommentsTextView = (TextView)findViewById(R.id.noCommentsTextView);
commentsTextView = (TextView)findViewById(R.id.commentsTextView);
mShareBtn = (FloatingActionButton) findViewById(R.id.share_floating_btn);
mFavBtn = (ToggleButton) findViewById(R.id.fav_news_btn);
imageButton = (ImageButton)findViewById(R.id.detail_comment_image_btn);
mRecyclerView = (RecyclerView)findViewById(R.id.recycler_comments);
LinearLayoutManager manager = new LinearLayoutManager(this);
mRecyclerView.setLayoutManager(manager);
mRecyclerView.setHasFixedSize(true);
mRecyclerView.addItemDecoration(new SimpleDividerItemDecoration(this));
commentArrayList = new ArrayList<>();
mDatabase = FirebaseDatabase.getInstance().getReference();
mFavBtn.setTextOn(null);
mFavBtn.setText(null);
mFavBtn.setTextOff(null);
newsAuthor = i.getStringExtra("author");
newsImage = i.getStringExtra("image");
newsTitle = i.getStringExtra("newsTitle");
newsDate = i.getStringExtra("date");
newsDescription = i.getStringExtra("description");
newsUrl = i.getStringExtra("url");
date1 = newsDate.substring(0, 10);
date2 = newsDate.substring(11, 19);
Picasso.with(this).load(newsImage)
.placeholder(R.drawable.ic_broken_image)
.into(mImageView);
mTitle.setText(newsTitle);
mAuthor.setText("Author: " + newsAuthor);
mDescription.setText(newsDescription);
mDate.setText(date2 + ", " + date1);
mShareBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent shareIntent = createShareNewsIntent();
startActivity(shareIntent);
}
});
imageButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent commentIntent = new Intent(DetailActivity.this, CommentActivity.class);
commentIntent.putExtra("newsTitle",newsTitle);
startActivity(commentIntent);
}
});
/**
* Handling the add/remove news part. We check if the specific news article
* exists in favourite.db.
*/
favoriteCursor = getContentResolver().query(FavouriteContract.FavouriteEntry.CONTENT_URI,
null,
FavouriteContract.FavouriteEntry.COLUMN_NEWS_TITLE + "=?",
new String[]{newsTitle},
null);
/**
* If yes then set the toggle button to true
*/
if (favoriteCursor.getCount() > 0) {
try {
mFavBtn.setChecked(true);
} finally {
favoriteCursor.close();
}
}
/**
* Else click the toggle button to add the news article as favourite
*/
mFavBtn.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton compoundButton, final boolean isChecked) {
/**
* If checked the add the news article as favourite.
*/
if (isChecked) {
new AsyncTask<Void, Void, Void>() {
#Override
protected Void doInBackground(Void... voids) {
ContentValues contentValues = new ContentValues();
contentValues.put(FavouriteContract.FavouriteEntry.COLUMN_NEWS_TITLE, newsTitle);
contentValues.put(FavouriteContract.FavouriteEntry.COLUMN_NEWS_AUTHOR, newsAuthor);
contentValues.put(FavouriteContract.FavouriteEntry.COLUMN_NEWS_DESCRIPTION, newsDescription);
contentValues.put(FavouriteContract.FavouriteEntry.COLUMN_NEWS_URL, newsUrl);
contentValues.put(FavouriteContract.FavouriteEntry.COLUMN_NEWS_URL_TO_IMAGE, newsImage);
contentValues.put(FavouriteContract.FavouriteEntry.COLUMN_NEWS_PUBLISHED_AT, newsDate);
//The actual insertion in the db.
uri = getContentResolver().insert(FavouriteContract.FavouriteEntry.CONTENT_URI, contentValues);
return null;
}
#Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
Toast.makeText(DetailActivity.this, "Article with title: " + newsTitle + " was added", Toast.LENGTH_SHORT).show();
}
}.execute();
} else {
/**
* If you uncheck the toggle button then delete the news article from the favourite db.
*/
Uri newsTitleOfFavNews = FavouriteContract.FavouriteEntry.buildNewsUriWithTitle(newsTitle);
//String title = uri.getPathSegments().get(1);// Get the task ID from the URI path
getContentResolver().delete(
newsTitleOfFavNews,
null,
null);
Toast.makeText(DetailActivity.this, "News article deleted from favourites ", Toast.LENGTH_SHORT).show();
}
}
});
queryFirebaseDb();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.detail_menu, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
super.onOptionsItemSelected(item);
if(item.getItemId() == R.id.detail_browser_btn){
Intent browserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse(newsUrl));
startActivity(browserIntent);
} if(item.getItemId() == android.R.id.home){
NavUtils.navigateUpFromSameTask(this);
return true;
}
return true;
}
private Intent createShareNewsIntent() {
Intent shareIntent = ShareCompat.IntentBuilder.from(this)
.setType("text/plain")
.setText(NEWS_SHARE_HASHTAG + "\n\n\n" + newsTitle
+ "\n\n\n" + newsDescription
+ "\n\n\n" + newsDate)
.getIntent();
return shareIntent;
}
#Override
protected void onStart() {
super.onStart();
//queryFirebaseDb();
}
#Override
protected void onRestart() {
super.onRestart();
queryFirebaseDb();
//displayCommentsAdapter.notifyDataSetChanged();
}
public void queryFirebaseDb(){
/**
* Querying the database to check if the specific article has comments.
*/
mDatabase = FirebaseDatabase.getInstance().getReference();
Query query = mDatabase.child("comments").orderByChild("newsTitle").equalTo(newsTitle);
query.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
if(dataSnapshot.exists()){
for(DataSnapshot dataSnapshots : dataSnapshot.getChildren()){
Comment comment = dataSnapshots.getValue(Comment.class);
//mUserDatabase = FirebaseDatabase.getInstance().getReference().child("Users").child(userId);
commentArrayList.add(comment);
displayCommentsAdapter = new DisplayCommentsAdapter(this,commentArrayList);
mRecyclerView.setAdapter(displayCommentsAdapter);
displayCommentsAdapter.setCommentsData(commentArrayList);
//Log.d(LOG_TAG, String.valueOf(commentArrayList.size()));
}
noCommentsTextView.setVisibility(View.GONE);
//commentsTextView.setVisibility(View.VISIBLE);
}else{
//Toast.makeText(DisplayComments.this,"There are no comments posted",Toast.LENGTH_LONG).show();
noCommentsTextView.setVisibility(View.VISIBLE);
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
/*
#Override
protected void onPause() {
super.onPause();
bundle.putBoolean("ToggleButtonState", mFavBtn.isChecked());
}
#Override
public void onResume() {
super.onResume();
mFavBtn.setChecked(bundle.getBoolean("ToggleButtonState",false));
}
*/
#Override
protected void onRestoreInstanceState(Bundle savedInstanceState) {
super.onRestoreInstanceState(savedInstanceState);
mFavBtn.setChecked(savedInstanceState.getBoolean("ToggleButtonState",false));
savedInstanceState.putParcelableArrayList("newsList",commentArrayList);
}
#Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putBoolean("ToggleButtonState",mFavBtn.isChecked());
outState.getParcelableArrayList("newsList");
}
}
and
public class CommentActivity extends AppCompatActivity {
private static final String REQUIRED = "Required";
private static final String TAG = CommentActivity.class.getSimpleName();
Toolbar toolbar;
DatabaseReference mDatabase;
EditText titleEt;
EditText bodyEt;
Button commentBtn;
String newsTitle;
Intent i;
String name;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_comment);
toolbar = (Toolbar) findViewById(R.id.comment_toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setTitle("Add comment");
mDatabase = FirebaseDatabase.getInstance().getReference();
titleEt = (EditText) findViewById(R.id.comment_title);
bodyEt = (EditText) findViewById(R.id.comment_body);
commentBtn = (Button) findViewById(R.id.comment_btn);
i = getIntent();
newsTitle = i.getStringExtra("newsTitle");
commentBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
submitPost();
}
});
}
private void submitPost() {
final String title = titleEt.getText().toString();
final String body = bodyEt.getText().toString();
// Title is required
if (TextUtils.isEmpty(title)) {
titleEt.setError(REQUIRED);
return;
}
// Body is required
if (TextUtils.isEmpty(body)) {
bodyEt.setError(REQUIRED);
return;
}
// Disable button so there are no multi-posts
setEditingEnabled(false);
Toast.makeText(this, "Posting...", Toast.LENGTH_SHORT).show();
// [START single_value_read]
final String userId = FirebaseAuth.getInstance().getCurrentUser().getUid();
mDatabase.child("Users").child(userId).addListenerForSingleValueEvent(
new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
// Get user value
User user = dataSnapshot.getValue(User.class);
// [START_EXCLUDE]
if (user == null) {
// User is null, error out
Log.e(TAG, "User " + userId + " is unexpectedly null");
Toast.makeText(CommentActivity.this,
"Error: could not fetch user.",
Toast.LENGTH_SHORT).show();
} else {
// Write new post
name = dataSnapshot.child("name").getValue().toString();
Calendar c = Calendar.getInstance();
SimpleDateFormat sdf = new SimpleDateFormat("dd-MM-yyyy hh:mm:ss");
String strDate = sdf.format(c.getTime());
writeNewPost(userId,strDate,name,newsTitle, title, body);
}
// Finish this Activity, back to the stream
setEditingEnabled(true);
finish();
// [END_EXCLUDE]
}
#Override
public void onCancelled(DatabaseError databaseError) {
Log.w(TAG, "getUser:onCancelled", databaseError.toException());
// [START_EXCLUDE]
setEditingEnabled(true);
// [END_EXCLUDE]
}
});
// [END single_value_read]
}
private void writeNewPost(String userId,String date,String
commentAuthor, String newsTitle, String commentTitle, String
commentBody){
String key = mDatabase.child("comments").push().getKey();
Comment comment = new Comment(userId, date,
commentAuthor,newsTitle,commentTitle,commentBody);
Map<String, Object> commentValues = comment.toMap();
Map<String, Object> childUpdates = new HashMap<>();
childUpdates.put("/comments/" + key, commentValues);
mDatabase.updateChildren(childUpdates);
}
private void setEditingEnabled(boolean enabled) {
titleEt.setEnabled(enabled);
bodyEt.setEnabled(enabled);
if (enabled) {
commentBtn.setVisibility(View.VISIBLE);
} else {
commentBtn.setVisibility(View.GONE);
}
}
}
UPDATE
I used this
#Override
protected void onRestart() {
super.onRestart();
finish();
startActivity(getIntent());
}
and voila!
Some stuff I thought you would know when doing Android:
Basically, in android, you need to understand how the life cycle works. So, when you call queryFirebaseDb() from onCreate and from onResume, your app is doing two queries at the same time when activity starts initially.
Lifecycle is like this OnCreate -> onResume. So, it makes sense that when activity starts, query gets executed once on onCreate than on onResume based on your logic.
Answer is here
I noticed that you are using ArrayList<Comment> commentArrayList;, which is an ArrayList structure, which lets you have duplicate data. And, if you look into the behavior of Firebase and how your query is structured, it is like this,
Query query = mDatabase.child("comments").orderByChild("newsTitle").equalTo(newsTitle);
This query means that you are taking all the comments, the previous comment and the new comment, (not just new comment), which I think you either just want (1) to get recently added comment or (2) to replace the old comments with new one.
The first way of doing this sounds complicated to me, though that is not impossible. But, second way of doing is rather easy.
Therefore, to solve this,
simply, replace the arrayList you have with this data.
if(dataSnapshot.exists()){
ArrayList<Comment> tempComments = new ArrayList();
for(DataSnapshot dataSnapshots : dataSnapshot.getChildren()){
Comment comment = dataSnapshots.getValue(Comment.class);
//mUserDatabase = FirebaseDatabase.getInstance().getReference().child("Users").child(userId);
tempComments.add(comment);
//Log.d(LOG_TAG, String.valueOf(commentArrayList.size()));
}
commentArrayList = tempComments; //assuming you want to store the data in the class fields
displayCommentsAdapter = new DisplayCommentsAdapter(this,commentArrayList);
mRecyclerView.setAdapter(displayCommentsAdapter);
displayCommentsAdapter.setCommentsData(commentArrayList);
noCommentsTextView.setVisibility(View.GONE);
//commentsTextView.setVisibility(View.VISIBLE);
}
I am trying to get the data to next activity using Bundle and putString. But the data fail to carry to the next page. Below is part of my coding:
public class assessment_table_edit extends AppCompatActivity {
Toolbar toolbar;
String data = "";
TableLayout tlAssessment;
TableRow tr;
TextView stuID,totalmarks,marks,edit;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_assessment_table_edit);
toolbar=(Toolbar)findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setTitle("Percentage of the Marks");
tlAssessment=(TableLayout)findViewById(R.id.tlAssessment_Edit);
final Assessment_Information_GetData getdb=new Assessment_Information_GetData();
new Thread(new Runnable() {
#Override
public void run() {
data =getdb.getDataFromDB();
System.out.println(data);
runOnUiThread(new Runnable() {
#Override
public void run() {
ArrayList<Assessment_Information> users=parseJSON(data);
addData(users);
}
});
}
}).start();
if(getSupportActionBar()!=null){
getSupportActionBar().setDisplayShowHomeEnabled(true);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
}
}
View.OnClickListener onClickListener=new View.OnClickListener() {
#Override
public void onClick(View v) {
switch (v.getId()){
case R.id.assessment_id:
Assessment_Information user=new Assessment_Information();
Intent iChange=new Intent(assessment_table_edit.this,assessment_edit_data.class);
Bundle b=new Bundle();
b.putString("stuID",user.getStuID());
iChange.putExtras(b);
// iChange.putExtra("stuID",user.getStuID());
startActivity(iChange);
break;
}
}
};
public ArrayList<Assessment_Information>parseJSON(String result){
ArrayList<Assessment_Information> users=new ArrayList<Assessment_Information>();
try {
JSONObject jsonObject=new JSONObject(result);
JSONArray jsonArray = jsonObject.getJSONArray("posts");
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject json_data = jsonArray.getJSONObject(i);
Assessment_Information user=new Assessment_Information();
user.setStuID(json_data.getString("stuID"));
user.setTotalmarks(json_data.getString("totalmarks"));
user.setMarks(json_data.getString("marks"));
users.add(user);
}
}catch (JSONException e){
Log.e("log_tag", "Error parsing data " + e.toString());
}
return users;
}
When I replace user.getString() to "check" for testing, it managed to show in the next activity(assessment_edit_data).
This is assessment_edit_data.java:
public class assessment_edit_data extends AppCompatActivity {
TextView tvMatrix;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_assessment_edit_data);
tvMatrix=(TextView)findViewById(R.id.edit_data_assessment);
Bundle bundle=getIntent().getExtras();
String stuID=bundle.getString("stuID");
tvMatrix.setText(stuID);
}
My Assessment_Information.java:
public class Assessment_Information {
String stuID;
String totalmarks;
String marks;
public String getStuID() {
return stuID;
}
public void setStuID(String stuID) {
this.stuID = stuID;
}
public String getTotalmarks() {
return totalmarks;
}
public void setTotalmarks(String totalmarks) {
this.totalmarks = totalmarks;
}
public String getMarks() {
return marks;
}
public void setMarks(String marks) {
this.marks = marks;
}
}
Use this code to send data to another activity:
Intent intent = new Intent(context, YourActivity.class);
intent.putExtra("key", "value");
intent.putExtra("key2", "value2");
startActivity(intent);
And use this code to get the data in the other Activity:
Bundle bundle = getIntent().getExtras();
if(bundle!=null){
String value1 = bundle.getString("key");
String value2 = bundle.getString("key2");
}
You can check if your bundle contains the key:
if(bundle.containsKey("key")){
//...
}
UPDATE
You're creating a new user without any data (it seems)
Assessment_Information user=new Assessment_Information(); //This user has data?
Intent iChange=new Intent(assessment_table_edit.this,assessment_edit_data.class);
Bundle b=new Bundle();
b.putString("stuID",user.getStuID()); // user.getStuID() probably is null
I don't see in your class Assessment_Information a constructor where you insert data to the stuID variable.
UPDATE
Try this part of code:
public class assessment_table_edit extends AppCompatActivity {
Toolbar toolbar;
String data = "";
TableLayout tlAssessment;
TableRow tr;
TextView stuID,totalmarks,marks,edit;
ArrayList<Assessment_Information> users;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_assessment_table_edit);
toolbar=(Toolbar)findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setTitle("Percentage of the Marks");
tlAssessment=(TableLayout)findViewById(R.id.tlAssessment_Edit);
final Assessment_Information_GetData getdb=new Assessment_Information_GetData();
new Thread(new Runnable() {
#Override
public void run() {
data =getdb.getDataFromDB();
System.out.println(data);
runOnUiThread(new Runnable() {
#Override
public void run() {
users=parseJSON(data);
addData(users);
}
});
}
}).start();
if(getSupportActionBar()!=null){
getSupportActionBar().setDisplayShowHomeEnabled(true);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
}
}
View.OnClickListener onClickListener=new View.OnClickListener() {
#Override
public void onClick(View v) {
switch (v.getId()){
case R.id.assessment_id:
Intent iChange=new Intent(assessment_table_edit.this,assessment_edit_data.class);
Bundle b=new Bundle();
b.putString("stuID", users.get(0).getStuID());
// If you want to send more than the first user
//for(int i=0; users.size() < i ; i++) {
// b.putString("stuID"+i, users.get(i).getStuID());
//}
//b.putInt("numberOfUsers", users.size());
iChange.putExtras(b);
// iChange.putExtra("stuID",user.getStuID());
startActivity(iChange);
break;
}
}
};
The problem it is you instantiate the user object but never retrieve the data. The user is as you declared it in the class.
At least you should read the data from you db and set it to the new object.
This is right way to putExtra and getExtra some data in Android.
Use this to "put" the file...
Intent i = new Intent(FirstScreen.this, SecondScreen.class);
String strName = null;
i.putExtra("STRING_I_NEED", strName);
Then, to retrieve the value try something like:
String newString;
Bundle extras = getIntent().getExtras();
if(extras == null) {
newString= null;
} else {
newString= extras.getString("STRING_I_NEED");
}
Bonus Suggestion :
I can see your class name is assessment_edit_data.
Make it like AssessmentEditData as Java suggest naming convention.
Kleorence,
I was shocked to see your huge code for adding a new row. I am giving you my code to add a new row with your desired styles and themes.
Pros:
Just code in .xml as you always do.
No need to code in java for styling rows.
in onCreate
TableLayout tableLayout = (TableLayout) findViewById(R.id.tlpromote);
private void addNewRow() {
// instantiate a tableRow
TableRow row = new TableRow(context);
// inflate your custom view on it.
View v = LayoutInflater.from(context).inflate(R.layout.table_row, row, false);
// put your values in its views
TextView tvTable_sr = (TextView) v.findViewById(R.id.tvTable_sr);
TextView tvTable_title = (TextView) v.findViewById(R.id.tvTable_title);
//add your custom view to row
tableLayout.addView(v);
}
Here table_row is your row with custom view.
<?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">
<!--make any view you want-->
</LinearLayout>
I hope you find this very helpful.
The problem is that you are populating the data in an array but when passing the object to another activity, you are creating a brand-new object in which every field is null.
public class assessment_table_edit extends AppCompatActivity {
Toolbar toolbar;
String data = "";
TableLayout tlAssessment;
TableRow tr;
TextView stuID,totalmarks,marks,edit;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_assessment_table_edit);
toolbar=(Toolbar)findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setTitle("Percentage of the Marks");
tlAssessment=(TableLayout)findViewById(R.id.tlAssessment_Edit);
//You are populating data here.
final Assessment_Information_GetData getdb=new Assessment_Information_GetData();
new Thread(new Runnable() {
#Override
public void run() {
data =getdb.getDataFromDB();
System.out.println(data);
runOnUiThread(new Runnable() {
#Override
public void run() {
ArrayList<Assessment_Information> users=parseJSON(data);
addData(users);
}
});
}
}).start();
if(getSupportActionBar()!=null){
getSupportActionBar().setDisplayShowHomeEnabled(true);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
}
}
View.OnClickListener onClickListener=new View.OnClickListener() {
#Override
public void onClick(View v) {
switch (v.getId()){
case R.id.assessment_id:
//Creating a new user in which every field is null/null object.
Assessment_Information user=new Assessment_Information();
Intent iChange=new Intent(assessment_table_edit.this,assessment_edit_data.class);
Bundle b=new Bundle();
//Passing an a field from the null object.
b.putString("stuID",user.getStuID());
iChange.putExtras(b);
// iChange.putExtra("stuID",user.getStuID());
startActivity(iChange);
break;
}
}
};
Try MarcGV's answer, or some variation of it to get some data.
Here is my codes in one activity that kept my database values in a textview:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_how_much);
myAuth = FirebaseAuth.getInstance();
myDatabase = FirebaseDatabase.getInstance().getReference();
hay=(TextView)findViewById(R.id.hay);
String user_id = myAuth.getCurrentUser().getUid();
DatabaseReference userid_database = myDatabase.child(user_id);
DatabaseReference book1 = userid_database.child("Books").child("Book 1").child("Page");
book1.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
String text = dataSnapshot.getValue(String.class);
hay.setText(text);
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
public void transfer(View view){
String value = hay.getText().toString();
Intent intent = new Intent(HowMuch.this, Basit.class);
intent.putExtra("key",value);
startActivity(intent);
}
This is my other activity codes:
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_basit);
textbasit=(TextView)findViewById(R.id.textbasit);
Bundle bundle=getIntent().getExtras();
String value = bundle.getString("key");
textbasit.setText(value);
}
This is my error:
in this line: String value = bundle.getString("key");
java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String android.os.Bundle.getString(java.lang.String)' on a null object reference
In my first activity value seems in "hay" textview. I want to get that value in another activity without using more textview to kept it by onDataChange method.
Add this to you other activity
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Intent intent = getIntent();
if(intent.hasExtra("key")){
textbasit.setText(intent.getStringExtra("key"));
}
}
You need to put a check on getIntent().getExtras() to see if it returning null
and also don't need to use bundle.
e.g.`
if (getIntent().getStringExtra("key") != null) {
String value = getIntent().getStringExtra("key");
textbasit.setText(value);
}
`
i wanna pass a string to all fragment(child) from fragment activity (main), may be this picture can explain what exactly what i want to do
https://dl.dropboxusercontent.com/u/57465028/SC20140205-163325.png
so, from above picture...i wanna pass a string from edittext by press a button to all activity in viewpager....how could i do that?
i tried to follow this code https://stackoverflow.com/a/12739968/2003393 but it can't solved my problem..
please help me...i'm stuck
thank in advance.
here is my code from fragment activity (MainActivity)
public class Swipe_Menu extends FragmentActivity {
//String KeyWord;
//private static final String KEYWORD = "keyword";
private ViewPager _mViewPager;
private ViewPagerAdapter _adapter;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.swipe_menu_image);
Button Back = (Button)findViewById(R.id.account);
ImageButton Search = (ImageButton)findViewById(R.id.search);
EditText Keyword = (EditText)findViewById(R.id.keyword);
final String KeyWord = Keyword.getText().toString();
/**
* Back button click event
* */
Back.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
finish();
}
});
setUpView();
setTab();
}
protected void sendValueToFragments(String value) {
// it has to be the same name as in the fragment
Intent intent = new Intent("my_package.action.UI_UPDATE");
intent.putExtra("UI_KEY", KeyWord );
LocalBroadcastManager.getInstance(this).sendBroadcast(intent);
}
and here is my fragment (Child Activity)
public class Store_Swipe extends Fragment {
public static final String ACTION_INTENT = "my_package.action.UI_UPDATE";
String KeyWord;
private TextView kata_keyword;
protected BroadcastReceiver receiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
if(ACTION_INTENT.equals(intent.getAction())) {
String value = intent.getStringExtra("UI_KEY");
updateUIOnReceiverValue(value);
}
}
};
private void updateUIOnReceiverValue(String value) {
// you probably want this:
KeyWord = value;
}
public static Fragment newInstance(Context context) {
Store_Swipe f = new Store_Swipe();
return f;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
IntentFilter filter = new IntentFilter(ACTION_INTENT);
LocalBroadcastManager.getInstance(getActivity()).registerReceiver(receiver, filter);
}
#Override
public void onDestroy() {
LocalBroadcastManager.getInstance(getActivity()).unregisterReceiver(receiver);
super.onDestroy();
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
/*Bundle bundle = this.getArguments();
KeyWord = bundle.getString("keyword");*/
View view = inflater.inflate(R.layout.store_swipe, container, false);
init(view);
return view;
}
void init(View view) {
kata_keyword = (TextView) view.findViewById(R.id.keyword);
//ImageView image = (ImageView) view.findViewById(R.id.image_error);
kata_keyword.setText(KeyWord);
}
}
You don't have access directly to your fragments that reside in ViewPager so you can't reference them directly.
What I am doing in these cases is send a broadcast message from Activity to Fragments. For this reason register a BroadcatReceiver in the fragment (either in onCreate or onCreateView - your decision)m, set a custom action for that receiver (ex. "my_package.actions.internal.BROADCAST_ACTION"), don't forget to unregister the receiver from complementary method.
When you want to send a message from activity, create an intent with above mentioned action, add the string in intent extra and send the broadcast.
In your receiver's onReceive method (within the fragment), get the String from intent paramter and there you have the string.
Makes sense?
EDIT: To provide some code, below are the changes that I would make for fragment:
public class Store_Swipe extends Fragment {
public static final String ACTION_INTENT = "my_package.action.UI_UPDATE";
protected BroadcastReceiver receiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
if(ACTION_INTENT.equals(intent.getAction())) {
String value = intent.getStringExtra("UI_KEY");
updateUIOnReceiverValue(value);
}
}
};
private void updateUIOnReceiverValue(String value) {
// you probably want this:
kata_keyword.setText(value);
}
String KeyWord;
private TextView kata_keyword;
public static Fragment newInstance(Context context) {
Store_Swipe f = new Store_Swipe();
return f;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
IntentFilter filter = new IntentFilter(ACTION_INTENT);
LocalBroadcastManager.getInstance(getActivity()).registerReceiver(receiver, filter);
}
#Override
public void onDestroy() {
LocalBroadcastManager.getInstance(getActivity()).unregisterReceiver(receiver);
super.onDestroy();
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
Bundle bundle = this.getArguments();
KeyWord = bundle.getString("keyword");
View view = inflater.inflate(R.layout.store_swipe, container, false);
init(view);
return view;
}
void init(View view) {
kata_keyword = (TextView) view.findViewById(R.id.keyword);
ImageView image = (ImageView) view.findViewById(R.id.image_error);
kata_keyword.setText(KeyWord);
}
}
And this code I would have from activity, the parameter is the value from EditText:
protected void sendValueToFragments(String value) {
// it has to be the same name as in the fragment
Intent intent = new Intent("my_package.action.UI_UPDATE");
intent.putExtra("UI_KEY", value);
LocalBroadcastManager.getInstance(this).sendBroadcast(intent);
}
You would call this from the click listener that you would set in onCreate:
findViewById(R.id.button_id).setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
String valueThatYouWantToSend = null; /// just the value
sendValueToFragments(valueThatYouWantToSend);
}
});
// I think this solution will solved your issue
// In Main activity put your code -----------------------------------
public void onPageSelected(int position)
{
System.out.println("nilesh");
PageOneFragment f = new PageOneFragment();
f.getText();
PageTwoFragment ff = new PageTwoFragment();
ff.setText();
}
//in General Class ------------------------------------------------
public class General
{
public static String name="";
}
// first Fragment ---------------------------------------------
public void getText()
{
General.name = edittext.getText().toString();
}
// second Fragment ----------------------------------------------
public void setText()
{
System.out.println("name**" + General.name);
tv.setText(General.name);
}