Unable to get the data to next activity - android

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.

Related

Android studio create listener to variable

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);
}
});

Pass Arraylist String using intent over 2 activities

I have 3 activities, activity 1 is fetching data from firebase, activity 2 is splash screen and activity 3 is show the data. I want to pass the data from activity 1 to activity 3 using intent. but it doesnt work. If i dont use activity 2 it works, but i want to use activity 2 as well.
Activity 1 fetching data from firebase
matchButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mDbref = FirebaseDatabase.getInstance().getReference();
mkomref = mDbref.child("Students");
string = matchKriteria.getText().toString();
Query query = mkomp.orderByChild("Komp").equalTo(string);
query.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
if (dataSnapshot.exists()) {
if(nameList.size()>0)
nameList.clear();
for (DataSnapshot data : dataSnapshot.getChildren()) {
nameList.add(data.child("Name").getValue(String.class));
}
Intent intent = new Intent(FirstActivity.this, LoadingActivity.class);
intent.putExtra("value",nameList);
startActivity(intent);
}
}
Activity 2 splash screen
public class LoadingActivity extends AppCompatActivity {
public static int SPLASH_TIME_OUT= 5000;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_loading);
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
Intent intent =new Intent(LoadingActivity.this, ResultActivity.class);
startActivity(intent);
finish();
}
},SPLASH_TIME_OUT);
Activity 3 show the result
public class ResultActivity extends AppCompatActivity {
private ArrayList<String> nameList;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_bedrift_match_resultat);
Intent intent = getIntent();
if (intent != null)
nameList = intent.getStringArrayListExtra("value");
RecyclerView recyclerView = (RecyclerView) findViewById(R.id.recycler_view);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
if (nameList.size() > 0) {
CustomAdapter adapter = new CustomAdapter(this, nameList);
recyclerView.setAdapter(adapter);
}
}
}
i think it didn't work because, in your LoadingActivity you didn’t retrieve data from FirstActivity and you’re not sending it to ResultActivity. So, your namelist in ResultActivity is null
You can try this:
public class LoadingActivity extends AppCompatActivity {
public static int SPLASH_TIME_OUT= 5000;
private ArrayList<String> nameList = new ArrayList<>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_loading);
if (getIntent() != null) {
namelist.addAll(getIntent().getStringArrayListExtra("value");
}
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
Intent intent =new Intent(LoadingActivity.this, ResultActivity.class);
intent.putExtra("value",nameList);
startActivity(intent);
finish();
}
},SPLASH_TIME_OUT);

Retrieve the data using putExtra [duplicate]

This question already has answers here:
How do I pass data between Activities in Android application?
(53 answers)
Closed 5 years ago.
I am doing admin page. I want to make changes to the data from server. The data already retrieved from server, but I do not know how to data can carry to the next activity(when i click Edit) using putExtra, because I use another java class to for retrieving the information. This is the sample of my table.
Below is my java 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);
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();
}
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,change_details.class);
//Having problem here
iChange.putExtra();
startActivity(iChange);
break;
}
}
};
Appreciate if some can enlighten me on how to use putExtra or other method to carry the data to another activity.
You can send data using,
Intent iChange = new Intent(assessment_table_edit.this,change_details.class);
iChange.putExtra("YOUR_KEY", "YOUR_VALUE");
startActivity(iChange);
You can get data using,
String data = getIntent().getStringExtra("YOUR_KEY");
You can pass your Object through Intent by using putExtra() method
if you want to pass arraylist then you can use putParcelableArrayListExtra()
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Intent i = new Intent(this,SecondActivity.class);
ArrayList<Assessment_Information> testing = new ArrayList<Assessment_Information>();
i.putParcelableArrayListExtra("extraextra", testing);
startActivity(i);
}
SecondActivity
public class SecondActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ArrayList<Assessment_Information> testing = this.getIntent().getParcelableArrayListExtra("extraextra");
}
}

expandable listview not loading after runOnUiThread

i am trying to bind data on a expandable listview. A new thread has been called because of too much load on the main thread during populate a map from database.
MY problem is, expandable list view is not showing after new thread
execution but if i set a break point on the adapter initialization ,
it working fine..i tried notifyDataSetChanged() but no luck
Activity
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_result);
Bundle extras = getIntent().getExtras();
if (extras == null) {
return;
}
selectedvalue = extras.getString("selected_data");
if (selectedvalue != null) {
TextView textView=(TextView)findViewById(R.id.textView2SelectedData);
textView.setText(selectedvalue);
textView.setBackgroundResource(R.color.colorAccent);
}
fillData();
ExpandableListView expandableListview =(ExpandableListView)findViewById(R.id.ExpandablelistSelectedData);
ExpandableListAdapter expandableListAdapter=new CustomAdapterExpandableList(this,manufacturerUnique,relatedMedicine);
expandableListview.setAdapter(expandableListAdapter);
}
public void fillData(){
manufacturerUnique=new ArrayList<>();
relatedMedList=new ArrayList<>();
relatedMedicine=new HashMap<>();
dbHelper=new DBHelper(this);
mProgressDialog = ProgressDialog.show(this, "Please wait","Loading...", false);
new Thread() {
#Override
public void run() {
try {
manufacturerUnique=dbHelper.getManfacturerNameListusingBrandOrGenericName(selectedvalue);
System.out.println("manufacturerUnique size"+manufacturerUnique.size());
for(int i=0;i<manufacturerUnique.size();i++){
relatedMedicine.put(manufacturerUnique.get(i),dbHelper.getBrandNameUsingSelectedItemAndmanfacturerName(selectedvalue,manufacturerUnique.get(i)));
System.out.println("manufacturerUnique added:"+manufacturerUnique.get(i));
}
System.out.println("related:"+relatedMedicine.size());
runOnUiThread(new Runnable() {
#Override
public void run() {
mProgressDialog.dismiss();
}
});
} catch (final Exception ex) {
Log.i("---","Exception in thread");
}
}
}.start();
}
}
What am i doing wrong here? I would greatly appreciate any feedback or pointing to a similar problem like this,thanks.
edit:
public class ResultActivity extends AppCompatActivity {
private DBHelper dbHelper=null;
ExpandableListView expandableListview;
String selectedvalue="";
List<String> manufacturerUnique;
List<String>relatedMedList;
Map<String,ArrayList<String>>relatedMedicine;
//ExpandableListAdapter expandableListAdapter;
BaseExpandableListAdapter expandableListAdapter;
private ProgressDialog mProgressDialog;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_result);
Bundle extras = getIntent().getExtras();
if (extras == null) {
return;
}
selectedvalue = extras.getString("selected_data");
if (selectedvalue != null) {
TextView textView=(TextView)findViewById(R.id.textView2SelectedData);
textView.setText(selectedvalue);
textView.setBackgroundResource(R.color.colorAccent);
}
fillData();
ExpandableListView expandableListview =(ExpandableListView)findViewById(R.id.ExpandablelistSelectedData);
expandableListAdapter=new CustomAdapterExpandableList(this,manufacturerUnique,relatedMedicine);
// expandableListAdapter.notifyDataSetChanged();
expandableListview.setAdapter(expandableListAdapter);
}
public void fillData(){
manufacturerUnique=new ArrayList<>();
relatedMedList=new ArrayList<>();
relatedMedicine=new HashMap<>();
dbHelper=new DBHelper(this);
mProgressDialog = ProgressDialog.show(this, "Please wait","Loading...", false);
new Thread() {
#Override
public void run() {
try {
manufacturerUnique=dbHelper.getManfacturerNameListusingBrandOrGenericName(selectedvalue);
System.out.println("manufacturerUnique size"+manufacturerUnique.size());
for(int i=0;i<manufacturerUnique.size();i++){
relatedMedicine.put(manufacturerUnique.get(i),dbHelper.getBrandNameUsingSelectedItemAndmanfacturerName(selectedvalue,manufacturerUnique.get(i)));
System.out.println("manufacturerUnique added:"+manufacturerUnique.get(i));
}
System.out.println("related:"+relatedMedicine.size());
// expandableListAdapter.notifyDataSetChanged();// exception
runOnUiThread(new Runnable() {
#Override
public void run() {
mProgressDialog.dismiss();
expandableListAdapter.notifyDataSetChanged();
}
});
} catch (final Exception ex) {
Log.i("---",ex.toString());
}
}
}.start();
}
}

passing data from (grand) parent to parent to child to (grand) child and back up to (Grand) parent activity in android

I have a grand parent activity called Department
public class Department extends AppCompatActivity {
RecyclerView recyclerView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_department);
.........
itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Context context = v.getContext();
Intent intent = new Intent(context, DeptDetail.class);
Bundle extra = new Bundle();
extra.putString("Department", getAdapterPosition()+"");
intent.putExtras(extra);
context.startActivity(intent);
}
});
}
}
Sends data about Department position to DepartmentDeatail activity
public class DeptDetail extends AppCompatActivity implements View.OnClickListener{
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_dept_detail);
Bundle extra = getIntent().getExtras();
deptpos = Integer.parseInt(extra.getString("Department"));
.........
public void onClick(View v) {
int id= v.getId();
Intent in;
Bundle extras = new Bundle();
in = new Intent(DeptDetail.this, Mission.class);
extras.putString("Mission",mission[deptpos]);
extras.putString("Deptid", deptpos+"");
in.putExtras(extras);
startActivityForResult(in,1);
}
}
and DeptDetail activity sends same Deptpos to its child activity Mission
public class Mission extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_mission);
Bundle extra = getIntent().getExtras();
String mission = extra.getString("Mission");
deptid=Integer.parseInt(extra.getString("Deptid"));
TextView txtmission = (TextView)findViewById(R.id.txtmission);
try {
txtmission.setText(mission);
}
catch (NullPointerException e)
{
txtmission.setText("");
}
}
}
And now I want same Deptid to be accessed in DeptDetail activity which always calls for intent from Department activity, which is not available as usual..
So please show me the way to pass the data to child and back to parent.
I tried
onActivityResult(..)
but it wasn't called before onCreate where extra is read and generating NullPointerException

Categories

Resources