How to send contents of Listview to another Activity? - android

I have a RelativeLayout with two TextViews inside it,the layout looks like a button. The user presses the "button" and I send one of the TextViews to a resulting TextView and the second TextView I put in a list. This is all done on the same activity. The user can keep pressing the "button" and it will populate the ListView with many items. My question is how do I send what's been populated in that resulting TextView and the ListView to a new activity. I'm able to send contents of the resulting TextView just fine but not getting anywhere with sending the contents of the ListView to new Activity.
This is the first Activity
public class MenuView1Activity extends ListActivity {
private double overallTotalproduct;
public static TextView resultTextView;
ArrayList<String> listItems=new ArrayList<String>();
ArrayAdapter<String> adapter;
private Button whateverButton;
TextView inputPrice;
RelativeLayout lay1;
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.menuview);
adapter=new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1,
listItems);
setListAdapter(adapter);
whateverButton = (Button)findViewById(R.id.whateverButton);
inputPrice= (TextView)findViewById(R.id.inputPrice);
lay1= (RelativeLayout)findViewById(R.id.lay1);
//Total Box
final TextView textViewtotalproduct = (TextView) findViewById(R.id.inputPrice);
final TextView textView1 = (TextView) findViewById(R.id.m1aa);
final String stringm1aa = textView1.getText().toString();
final double intm1aa = Double.parseDouble(stringm1aa);
final TextView textView1a = (TextView) findViewById(R.id.m1a);
final String stringm1a = textView1a.getText().toString();
lay1.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
listItems.add("$"+intm1aa +"-"+ stringm1a);
adapter.notifyDataSetChanged();
resultTextView.setText(stringm1a);
overallTotalproduct = intm1aa + overallTotalproduct;
textViewtotalproduct.setText(String.valueOf(overallTotalproduct));
}
});
public void onwhateverPress(View v) {
Intent whateverIntent = new Intent(this, WhateverActivity.class);
if (whateverResult.iswhateveranicewhatever()) {
final TextView daplane =(TextView)findViewById(R.id.date);
String watch = daplane.getText().toString();
startActivity(new Intent(MenuView1Activity.this,RecordCheckActivity.class)
.putExtra("date",(CharSequence)watch)
.putStringArrayListExtra("list", (ArrayList<String>) listItems));
finish();
And the Second one
Intent id11 = getIntent();
if (id11.getCharSequenceExtra("list") != null) {
final TextView setmsg = (TextView)findViewById(R.id.saleNotes);
setmsg.setText(id11.getCharSequenceExtra("list"));
}

you can get all updated items from ListView using ListView.getAdapter() then use Intent.putStringArrayListExtra for sending ArrayList from one Activity to other:
startActivity(new Intent(MenuView1Activity.this,RecordCheckActivity.class)
.putExtra("date",(CharSequence)watch)
.putStringArrayListExtra("list", (ArrayList<String>)getListView().getAdapter()));
finish();

Related

Return different list depending on edittext String

I'm trying to display a listview conatining clothes items ..the listview will appear after the button "enter" under edittext will be clicked ..thelistitems will be different depending on what is the string(colors) on edittext (PS: the string in Listview are name and refrence of clothes!)..
for exemple:
if user choses in edittext: "Color1, Color2, "
a list will appear with a name and refrence of clothes that contain those colors: "Item1, Item2"
Because Item1 and Item2 are the only ones to contain the color1 and color2!
The list of possible Items(clothes) are 100, and Possible input in edit text are 6 colors (Color1, Color2, Color3, Color4, Color5, Color6) ..every time the user choses a set of color, the list will be displayed with the possible Items than contain those colors! ( as explained here: https://i.imgur.com/XwHTmGY.png)
PS: i've already created a custom edittext and use the adapter with the different strings(Color1..Color6) and i know how to get the string from the edittext ..but how to create update the listview with different items w depending on the string(chosen colors) of the edittext is the priblem! Thanks!
How to that? i've searched on internet on similar exemples with no luck..
This is my code so far:
MainActivity.java
public class DecisionTree extends AppCompatActivity {
private static final String TAG = DecisionTree.class.getSimpleName();
TextView txt,txt2;
com.mycardboarddreams.autocompletebubbletext.MultiSelectEditText editText;
String data;
private ListView listView;
private ItemAdapter itemListAdapter;
private List<Item> itemList = new ArrayList<Item>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_decision_tree);
/////////////////////////////////////////////////
listView = (ListView) findViewById(R.id.diseases_list_container);
itemListAdapter = new ItemAdapter(itemList, this);
listView.setAdapter(itemListAdapter);
listView.setFastScrollEnabled(true);
////////////////////////////////////////////////
// add some items
itemList.add(new Item("Jeans Refnum 2520"));
itemList.add(new Item("T shirt Refnum 1220"));
.
.
.
.
.
A long list of 100 items
//add new items and changes to adapter
itemListAdapter.notifyDataSetChanged();
////////////////////////////////////////////////
//Text
txt = (TextView) findViewById(R.id.textView);
txt2 = (TextView) findViewById(R.id.textView2);
txt.setText("Given a set of clinical features, this tool should provide you with a reasonable and relevant differential diagnsosis (not the definitive diagnosis!)");
txt2.setText("Remember, this tool adds to your diagnostic skills and serves as an educational aid. It is not meant to replace your clinical judgement.");
//the edittext
editText = (com.mycardboarddreams.autocompletebubbletext.MultiSelectEditText) findViewById(R.id.auto_text_complete);
//Add some sample items
List<SampleItem> sampleItems = Arrays.asList(
new SampleItem("Blue"),
new SampleItem("Red"),
new SampleItem("Orange"),
new SampleItem("Yellow"),
new SampleItem("vert"),
new SampleItem("rouge")
);
editText.addAllItems(sampleItems);
//Get the ListView associated with the MultiSelectEditText
ListView list = editText.getListView();
//Add it to a FrameLayout somewhere in the activity
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);
list.setLayoutParams(params);
final FrameLayout frame = (FrameLayout) findViewById(R.id.auto_list_container);
frame.addView(list);
// The output
//frameLayout = (FrameLayout) findViewById(R.id.auto_list_container2);
//Set a listener on bubble clicks
//editText.setBubbleClickListener(new com.mycardboarddreams.autocompletebubbletext.MultiSelectEditText.BubbleClickListener<SampleItem>() {
/* #Override
public void onClick(SampleItem item) {
//Log.d(TAG, "Item: " + item.getReadableName());
Toast.makeText(DecisionTree.this, item.getReadableName(),
Toast.LENGTH_LONG).show();
//displayListPatho();
}
});*/
//-----------------------------------------END ONCREATE
}
public void blahblah (View view) {
data= editText.getText().toString();
listView.setVisibility(View.VISIBLE);
Toast.makeText(DecisionTree.this, data,
Toast.LENGTH_LONG).show();
}
I acheived what i want with making this code:
1/ created a list with adapter
2/ on each click the items on adapter are removed( clearAdapter();) and new items are added (itemList.add(new Item("Jenny"));) depending on string from edit text( if (data.equals("Epistaxis, ")). and after the adapter is notified with itemListAdapter.notifyDataSetChanged();
Ps: blahblah (=Button OnClick) ..
public void blahblah (View view) {
data= editText.getText().toString();
if (data.equals("Epistaxis, ")){
clearAdapter();
itemList.add(new Item("Jenny"));
itemList.add(new Item("Bladna"));
itemList.add(new Item("Drafat"));
itemListAdapter.notifyDataSetChanged();
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
// TODO Auto-generated method stub
if (position == 0) {
Intent i=new Intent(DecisionTree.this, Figures.class);
startActivity(i);
} else if (position == 1) {
//code specific to 2nd list item
Toast.makeText(getApplicationContext(), "Place Your Second Option Code", Toast.LENGTH_SHORT).show();
} else if (position == 2) {
Toast.makeText(getApplicationContext(), "Place Your Third Option Code", Toast.LENGTH_SHORT).show();
}
}
}); }
else if (data.equals("Nasal Discharge, ")) {
clearAdapter();
itemList.add(new Item("Jenny2"));
itemList.add(new Item("Bladna2"));
itemList.add(new Item("Drafat2"));
itemListAdapter.notifyDataSetChanged();
}
Very long question, but it's not clear exactly what do you want?
If I understand right, you should do somthing like that:
Get your String string from EditText.
String[] items = string.split(" ");
ListView listView = (ListView)findViewById(R.id.listView);
ArrayAdapter<String> adapter = new ArrayAdapter<>(this,
android.R.layout.simple_list_item_1, items);
listView.setAdapter(adapter);
What a problem with that?

Generating a ListView Using ArrayAdapter [duplicate]

This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 5 years ago.
I am trying to populate a ListView using an ArrayAdapter that I am filling with input from an EditText. My program seems to compile fine but during app start up it immediately crashes. I suspect that it has something to do with me trying to set-up my list view. I am not sure what I am initializing wrong such that my app instantly crashes. Any and all tips would be greatly appreciated. Thanks in advance!
This is my global declarations for my ArrayList and Adapter.
ArrayList<scoreScreen> savedScores = new ArrayList<>();
ScoreAdapter adapter = new ScoreAdapter(this, savedScores);
ListView listView = (ListView) findViewById(R.id.dispScores);
listView.setAdapter(adapter);
My Adapter Class:
private class ScoreAdapter extends ArrayAdapter<scoreScreen> {
private ScoreAdapter(Context context, ArrayList<scoreScreen> scores) {
super(context, 0, scores);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
scoreScreen score1 = getItem(position);
if (convertView == null){
convertView = LayoutInflater.from(getContext()).inflate(R.layout.item_scores, parent, false);
}
TextView holeNum = (TextView) convertView.findViewById(R.id.holeNum);
holeNum.setText(score1.hole);
return convertView;
}
}
My ListView inside of my onCreate method.
ListView listview = (ListView) findViewById(R.id.listView1);
listview.setAdapter(adapter);
I am assuming my problem is not inside my EditText inputs since they are inside of an OnClickListener method, but just incase I have attached it below.
public View.OnClickListener onClickListener = new View.OnClickListener() {
#Override
public void onClick(View view) {
EditText input1 = (EditText) findViewById(R.id.scorePrompt);
TextView output1 = (TextView) findViewById(R.id.textTotal);
String blankCheck = input1.getText().toString(); //CHANGE INPUT IN scorePrompt TO STRING
switch (view.getId()) {
case R.id.buttTotal:
if (blankCheck.equals("")) {
Toast blankError = Toast.makeText(getApplicationContext(), "YOU CANT SKIP HOLES JERK", Toast.LENGTH_LONG);
blankError.show();
break;
} else {
int num1 = Integer.parseInt(input1.getText().toString()); //Get input from text box
int sum = num1 + score2;
score2 = sum;
output1.setText("Your score is : " + Integer.toString(sum));
//savedScores.add(input1.getText().toString());
scoreScreen addScore = new scoreScreen("Score is" + num1);
adapter.add(addScore);
j++;
input1.setText(""); //Clear input text box
break;
}
case R.id.allScores: //CHANGE THIS TO AN EDIT BUTTON, ADD A HOLE NUMBER COUNTER AT TOP OF SCREEN!!!!!
output1.setText("you messed up");
break;
case R.id.editScore: //Need to set up Save Array before we can edit
//CURRENTLY ONLY DISPLAYS THE LAST NUNMBER IN THE TEXTEDIT, NEED TO SET UP LISTVIEW!!!!!!
for (int i=0; i < j; i++){
// output1.setText(savedScores.get(i));
} break;
}
}
};
onCreate method added as requested:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
/*Button scoresAct = (Button) findViewById(R.id.allScores); //THIS IS TO GO TO ALL SCORES ACTIVITY
scoresAct.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent scoreScreen = new Intent(MainActivity.this, AllScoresAct.class);
startActivity(scoreScreen);
}
});*/
Button sumScores = (Button) findViewById(R.id.buttTotal);
Button saveScores = (Button) findViewById(R.id.allScores);
Button changeScores = (Button) findViewById(R.id.editScore);
sumScores.setOnClickListener(onClickListener);
saveScores.setOnClickListener(onClickListener);
changeScores.setOnClickListener(onClickListener);
ListView listview = (ListView) findViewById(R.id.listView1);
listview.setAdapter(adapter);
}
After moving my adapter and ArrayList into my onCreate, I get a new error. I did some research on null pointers, but I have already initialized both of these. Below is my logcat, any ideas? Thanks
Make sure super.onCreate(savedInstanceState) is the first thing you are calling in your onCreate() and also not trying to access any view from the layout xml before setContentView().
EDIT:
Initialize the adapter in onCreate() method instead of doing it globally.
onCreate() {
.......
this.adapter = new ScoreAdapter(this, savedScores);
}
This is my global declarations for my ArrayList and Adapter.
ArrayList<scoreScreen> savedScores = new ArrayList<>();
ScoreAdapter adapter = new ScoreAdapter(this, savedScores);
You can declare those globally, but for the Adapter, the this parameter must be used within/after onCreate, as the error says
System services not available to Activities before onCreate()
For example
private ArrayList<ScoreScreen> savedScores = new ArrayList<>();
private ScoreAdapter adapter;
#Override
protected void onCreate(Bundle b) {
...
adapter = new ScoreAdapter(this, savedScores);
}

use if-statement to recognize arraylist data in android

i want to use condition " if " for my array list
here is my code in (activity 1) to send string in textview with button to static variable that is in (exchange activity) :
Button btn1 = (Button) findViewById(R.id.btn1);
final TextView text = (TextView) findViewById(R.id.txt1);
btn1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
exchange.in =text.getText().toString();
}
});
here is my static variable in (exchange activity)
public static String in;
and here is my (activity 2) code that i use array list in it to receive & store string from (activity 1) that is in static variable (exchange.in)
ListView list;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ArrayList<String> web = new ArrayList<String>(10);
for (int i = 0; i < 10; i++) {
web.add("");
}
CustomList adapter = new
CustomList(activity_main.this, web);
list = (ListView) findViewById(R.id.list);
list.setAdapter(adapter);
}
now i don't know how to store data from (exchange.in) to arraylist and then use if condition to recognize that, if arraylist(0) was full, put data that is in (exchange.in) to arraylist(1) and it will continue like this...
is anyone know about this?

how to get the edit text value out of an editable listview

I created an editable custom listview with a button outside the listview. I want to save the editText value entered by the user on the button click. My edit text is in base Adapter class and my list and button is in activity class, i'm having problem accessing the edit text from the list and my code crashes because of null pointer exception
public class ProductsList extends Activity{
ProductListAdapter dataAdapter;
ProgressDialog progressDialog=null;
ListView listView;
UserSQLiteDB usersqlite_obj;
ArrayList<Products> prodlist;
EditText edChemistName, edChemistAddr;
Button btnSave;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.productlist);
edChemistName = (EditText) findViewById(R.id.editText1);
edChemistAddr = (EditText) findViewById(R.id.editText2);
btnSave =(Button)findViewById(R.id.button1);
listView = (ListView)findViewById(R.id.listView1);
usersqlite_obj = new UserSQLiteDB(this);
progressDialog = ProgressDialog.show(this, "Saved","Please wait...", true);
// new Thread() {
runOnUiThread(new Runnable() {
public void run() {
try{
usersqlite_obj.open();
prodlist = new ArrayList<Products>();
prodlist = usersqlite_obj.getProductsList();
Log.e("prodlist", "1");
dataAdapter = new ProductListAdapter(ProductsList.this,prodlist);
listView.setAdapter(dataAdapter);
usersqlite_obj.close();
} catch (Exception e) {
Log.d("error",e.getMessage());
}
dismissLoadingDialog();
}
});
}
public void buttonClick(View V) {
for(int i=0;i<listView.getCount();i++){
View row = listView.getChildAt(i);
Log.e("editText clicked", "yes");
EditText editText= (EditText) row.findViewById(R.id.ed);
if (editText.length()>0){
String text = editText.getText().toString();
Log.e("extracted text", "text");
}
}
If u want to use edittext data of listview in ur adapter class then u should pass this liatview in adapter class or you can set this adapter in activty file.

android ListActivity onListItemClick to open data in another activity

Hey I have tried to make a ListActivity that show the internal saved data, there have been saved from another activity. And when I click on an item, it should open a new activity with the internal data, and then open the data.
Here is the first activity. there shall show the listview and when clicked on an item, the user should be send to second activity whith more details
public class ShowListActivity extends ListActivity {
private ArrayAdapter<String> list;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_show_data);
getListView().setChoiceMode(ListView.CHOICE_MODE_SINGLE);
getListView().setSelector(android.R.color.holo_blue_bright);
String[] filenames = getApplicationContext().fileList();
List<String> list = new ArrayList<String>();
for(int i = 0; i<filenames.length; i++){
//Log.d("Filename", filenames[i]);
list.add(filenames[i]);
}
setListAdapter(new ArrayAdapter(this,
android.R.layout.simple_list_item_1, list));
}
protected void onListItemClick(ListView l, View v, int position, long id) {
super.onListItemClick(l, v, position, id);
String product = ((TextView)v).getText().toString();
Intent i = new Intent(getApplicationContext(), MainActivity.class);
i.putExtra("product", product);
startActivity(i);
}
Here is the other activity there shall recived the data and open it.
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
ActionBar actionBar = getActionBar();
actionBar.setDisplayHomeAsUpEnabled(true);
actionBar.setDisplayShowTitleEnabled(true);
TextView showCloseRange = (TextView) findViewById(R.id.show_close_range);
TextView showToRight = (TextView) findViewById(R.id.show_to_right);
TextView showToCenterRight = (TextView) findViewById(R.id.show_to_center_right);
TextView showToCenter = (TextView) findViewById(R.id.show_to_center);
TextView showToCenterLeft = (TextView) findViewById(R.id.show_to_center_left);
TextView showToLeft = (TextView) findViewById(R.id.Show_to_left);
TextView showFT = (TextView) findViewById(R.id.show_ft);
TextView showTreRight = (TextView) findViewById(R.id.show_tre_right);
TextView showTreCenterRight = (TextView) findViewById(R.id.show_tre_center_right);
TextView showTreCenter = (TextView) findViewById(R.id.show_tre_center);
TextView showTreCenterLeft = (TextView) findViewById(R.id.show_tre_center_left);
TextView showTreLeft = (TextView) findViewById(R.id.show_tre_left);
TextView showAssist = (TextView) findViewById(R.id.show_assist);
TextView showSteals = (TextView) findViewById(R.id.show_steals);
TextView showFouls= (TextView) findViewById(R.id.show_fouls);
TextView showTotalPt = (TextView) findViewById(R.id.show_total_pt);
TextView showDataBlocks = (TextView) findViewById(R.id.show_data_blocks);
TextView showDataRebounds = (TextView) findViewById(R.id.show_data_rebounds);
TextView showDataTurnOcers = (TextView) findViewById(R.id.show_data_turn_overs);
TextView showDataPlayerTime = (TextView) findViewById(R.id.show_data_player_time);
TextView showNote = (TextView) findViewById(R.id.show_note);
String value = "";
FileInputStream fis;
Intent i = getIntent();
String product = i.getStringExtra("product");
ActionBar actionBar1 = getActionBar();
actionBar1.setTitle(product);
try {
fis = openFileInput(product);
byte[] input = new byte[fis.available()];
while(fis.read(input) != -1){
value += new String(input);
fis.close(); }
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
String[] strArray = value.split(";");
showCloseRange.setText(strArray[0]);
showToRight.setText(strArray[1]);
showToCenterRight.setText(strArray[2]);
showToCenter.setText(strArray[3]);
showToCenterLeft.setText(strArray[4]);
showToLeft.setText(strArray[5]);
showFT.setText(strArray[6]);
showTreRight.setText(strArray[7]);
showTreCenterRight.setText(strArray[8]);
showTreCenter.setText(strArray[9]);
showTreCenterLeft.setText(strArray[10]);
showTreLeft.setText(strArray[11]);
showDataPlayerTime.setText(strArray[12]);
showTotalPt.setText(strArray[13]);
showAssist.setText(strArray[14]);
showSteals.setText(strArray[15]);
showDataBlocks.setText(strArray[16]);
showDataRebounds.setText(strArray[17]);
showDataTurnOcers.setText(strArray[18]);
showFouls.setText(strArray[19]);
showNote.setText(strArray[20]);
}
I have trouble with sending the data between the activies and open it, so it will split up in my many differents textviews.
Any ideas ?
And sorry for my bad English
Try this way,hope this will help you to solve your problem.
Instead of geting product from ListView item TextView just declare your ArrayList object outside oncreate() and try to get your particular product using position from list in ListView item click listener.
public class ShowListActivity extends ListActivity {
private List<String> list = new ArrayList<String>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_show_data);
getListView().setChoiceMode(ListView.CHOICE_MODE_SINGLE);
getListView().setSelector(android.R.color.holo_blue_bright);
list = Arrays.asList(getApplicationContext().fileList());
setListAdapter(new ArrayAdapter(this,android.R.layout.simple_list_item_1, list));
}
protected void onListItemClick(ListView l, View v, int position, long id) {
super.onListItemClick(l, v, position, id);
Intent i = new Intent(this, MainActivity.class);
i.putExtra("product", list.get(position));
startActivity(i);
}
}
You can check what you are sending to second activity, mean using System.out.println() you can check on logcat . Also i done small change in your code please try this.
private ArrayAdapter<String> list;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_show_data);
getListView().setChoiceMode(ListView.CHOICE_MODE_SINGLE);
getListView().setSelector(android.R.color.holo_blue_bright);
String[] filenames = getApplicationContext().fileList();
ArrayList<String> arrlist = new ArrayList<String>();
for(int i = 0; i<filenames.length; i++){
//Log.d("Filename", filenames[i]);
arrlist.add(filenames[i]);
}
setListAdapter(new ArrayAdapter(this,
android.R.layout.simple_list_item_1, arrlist ));
}
protected void onListItemClick(ListView l, View v, int position, long id) {
super.onListItemClick(l, v, position, id);
String product = arrlist.get(position);
//Here you can check what yo are sending to second activity using System.out.println
System.out.println("click product is : "+product);
Intent i = new Intent(getApplicationContext(), MainActivity.class);
i.putExtra("product", product);
startActivity(i);
finish();
}
Ans also in other activity mean second activity you can add System.out.println to check list item value is coming or not.
String product = getIntent().getStringExtra("product");
System.out.println("product in second activity : "+product);

Categories

Resources