Pass Arraylist String using intent over 2 activities - android

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

Related

How can I send array from one activity (intent) to another?

list.addAll(paireDevice);
Intent i= new Intent(bluetooth.this, ShowPairedDevice.class);
i.getParcelableArrayListExtra("Device.list",(ArrayList<?extends Parcelable>)list);
startActivity(i);
try this:
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ArrayList<String> list = new ArrayList<>();
list.add("Device1");
list.add("Device2");
list.add("Device3");
Intent i = new Intent(this, NewActivity.class);
i.putExtra("Device.list", list);
startActivity(i);
}
}
public class NewActivity extends AppCompatActivity {
private String TAG = NewActivity.class.getSimpleName();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_new);
ArrayList<String> list = (ArrayList<String>) getIntent().getSerializableExtra("Device.list");
for (String device: list){
Log.i(TAG, "Devices: " + device);
}
}
}
now it's work with the was in getParcelableArrayListExtra instead ofputParcelableArrayListExtra
list.addAll(paireDevice); Intent i= new Intent(bluetooth.this, ShowPairedDevice.class); i.putParcelableArrayListExtra("Device.list", (ArrayList) list); startActivity(i);

Listview does not populate first time

I'm creating a ListView by populating an ArrayList in open activity and opening it as a ListView in another activity.
When I open the second activity My ListView only populates when I open the activity, the Get_Issue activity opens blank. When I go back and re-enter the activity (Calling the Get_Issue.class for the second time). Then the ListViewis populated.
I guess the screen is loading before the listView is created/populated?
How can I improve my code so that the listView is populate the first time I call the Get_Issue activity. I do not want to open an empty activity.
class ProfileActivity extends AppCompatActivity implements View.OnClickListener {
DatabaseReference databaseIssue;
public static List<Issue> issueList = new ArrayList<>();
public static List<Issue> getIssueList() {
return issueList;
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_profile);
getData = (Button) findViewById(R.id.getData);
databaseIssue = FirebaseDatabase.getInstance().getReference("Issue");
}
private void getTheData(){
databaseIssue.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
issueList.clear();
for (DataSnapshot postSnapshot : dataSnapshot.getChildren()) {
Issue getData = postSnapshot.getValue(Issue.class);
issueList.add(getData);}}
});
}
public void onClick(View view) {
if(view == getData){
getTheData();
startActivity(new Intent(this, Get_Issue.class));
}
}
}
The adapter class
public class Get_Issue extends AppCompatActivity {
public void populateListView() {
List<Issue> issues = ProfileActivity.getIssueList();
ArrayAdapter<Issue> adapter = new ArrayAdapter<>(
this,
R.layout.da_item,
issues);
ListView list = findViewById(R.id.listView);
list.setAdapter(adapter);
}
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.issue_list);
populateListView();
}
}

Unable to get the data to next activity

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.

Intent - null Pointer Exception

I try to make my own gallery. User can add a rating to every photo.
I want something like this: Main class put all photos on a screen. User click a photo then he can add a rating. Click back button on phone and main class refresh a rating, but intent is always null. Take a look on comments in code.
//My main class.
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
recyclerView = (RecyclerView)findViewById(R.id.imagegallery);
recyclerView.setHasFixedSize(true);
RecyclerView.LayoutManager layoutManager = new GridLayoutManager(getApplicationContext(),2);
recyclerView.setLayoutManager(layoutManager);
createLists = prepareData();
adapter = new MyAdapter(getApplicationContext(), createLists);
recyclerView.setAdapter(adapter);
}
//My Adapter class from I send an Intent.
public MyAdapter(Context context, ArrayList<CreateList> galleryList) {
this.galleryList = galleryList;
this.context = context;
}
#Override
public MyAdapter.ViewHolder onCreateViewHolder(ViewGroup viewGroup, int i) {
View view = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.photo_layout, viewGroup, false);
return new ViewHolder(view);
}
#Override
public void onBindViewHolder(final MyAdapter.ViewHolder viewHolder, final int i) {
viewHolder.title.setText(galleryList.get(i).getImage_title());
stars = (RatingBar) viewHolder.itemView.findViewById(R.id.ratingBar1);
stars.setRating(galleryList.get(i).getStars());
Picasso.with(context)
.load(galleryList.get(i)
.getImage_ID()).centerCrop()
.resize(240, 240)
.onlyScaleDown()
.into(viewHolder.img);
viewHolder.img.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent nextScreen = new Intent(context, ShowPhotoActivity.class);
nextScreen.putExtra("fullPhoto", galleryList.get(i));
nextScreen.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(nextScreen); //everything is OKAY
}
});
}
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.show_photo_activity_layout);
fullPhoto = (CreateList) getIntent().getSerializableExtra("fullPhoto"); //IS OKAY
photoID = fullPhoto.getImage_ID();
stars = (RatingBar)findViewById(R.id.ratingBar);
stars.setRating(fullPhoto.getStars());
if(savedInstanceState != null){
stars.setNumStars(savedInstanceState.getInt(starsPoint));
}
mImageView = (ImageView) findViewById(photoID);
mImageView = (ImageView) findViewById(R.id.image1);
mImageView.setImageResource(photoID);
//message = new Intent(getApplicationContext(), MainActivity.class);
stars.setOnRatingBarChangeListener(new RatingBar.OnRatingBarChangeListener() {
public void onRatingChanged(RatingBar ratingBar, float rating,
boolean fromUser) {
fullPhoto.set_Stars(rating);
message = new Intent(getApplicationContext(), MainActivity.class);
message.putExtra("Photo", fullPhoto);
message.setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP | Intent.FLAG_ACTIVITY_CLEAR_TOP);
System.out.println(fullPhoto.getStars()); //OKAY
startActivity(message);
}
});
}
//Now we are in main class. ALWAYS null. I've tried every solution on stack
#Override
protected void onNewIntent(Intent intent) {
super.onNewIntent(intent);
CreateList photo = (CreateList) getIntent().getSerializableExtra("Photo"); //NULL
for(CreateList photoTemp : createLists) {
if (photoTemp.getImage_ID() == photo.getImage_ID()) {
photoTemp.set_Stars(photo.getStars());
}
}
}
Use onNewIntent callback provides intent parameter instead of call getIntent() method, so, your code must be like the follow:
#Override
protected void onNewIntent(Intent intent) {
super.onNewIntent(intent);
CreateList photo = (CreateList) intent.getSerializableExtra("Photo");
for(CreateList photoTemp : createLists) {
if (photoTemp.getImage_ID() == photo.getImage_ID()) {
photoTemp.set_Stars(photo.getStars());
}
}
}

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