Android Add Listview item dynamically? - android

i want to add listview item dynamically. i had done this but when i restart the app listview item disappear. How can i save this item permanently to listview. please suggest
public class ChatWithAttorney extends Activity {
ImageView btnBack;
ListView chatList;
EditText etMsg;
Button btnSend;
String msg_to_send;
ArrayAdapter<String> adapter;
ArrayList<String> listMsg;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.chatwithattorny);
btnBack = (ImageView) findViewById(R.id.btnback);
chatList = (ListView) findViewById(R.id.chatList);
etMsg = (EditText) findViewById(R.id.etMsg);
btnSend = (Button) findViewById(R.id.btnSend);
listMsg = new ArrayList<String>();
adapter = new ArrayAdapter<String>(this, R.layout.chat_list_text, R.id.tvSentMsg,listMsg);
chatList.setAdapter(adapter);
btnSend.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
try {
msg_to_send = URLEncoder.encode(etMsg.getText().toString(),
"utf-8");
listMsg.add(msg_to_send);
adapter.notifyDataSetChanged();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
}
});
}

Put those ArrayList items in a database or SharedPreference and read those items when resuming your activity.

You can use Local database , SharedPreference or Static arraylist for storing the messages

AT the Time of Destroy Serialize the List data.
And Deserilize when Application Starts Again.

Related

Adding a Item to Listview

Im trying to simply add a Item to a Listview and display it. But if I add it it just shows me the path of that string istead of the tring itself. I'm sure it's a simple mistake but I cant find it.
public class zutatenHinzufuegen extends AppCompatActivity {
private ArrayList<String> zutatenliste;
private ListView zutatenView;
private ArrayAdapter<String> zutatenadapter;
private TextInputLayout zutatInput;
private TextInputLayout anzahlInput;
private int anzahlint;
private String einheitInput;
private Button hinzufuegen_button;
#Override
protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.zutaten_hinzufuegen_linear);
getSupportActionBar().setTitle(R.string.menu_zutaten);
// Spinner
final Spinner einheiten_spinner = (Spinner) findViewById(R.id.spinner_einheiten2);
ArrayAdapter<String> einheiten_adapter = new ArrayAdapter<String>(zutatenHinzufuegen.this,
android.R.layout.simple_list_item_1,getResources().getStringArray(R.array.einheiten));
einheiten_adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
einheiten_spinner.setAdapter(einheiten_adapter);
// List
zutatInput =(TextInputLayout) findViewById(R.id.textInputZutat2);
einheitInput =(String) einheiten_spinner.getSelectedItem().toString();
anzahlInput = (TextInputLayout) findViewById(R.id.textInputAnzahl2);
try {
anzahlint = Integer.parseInt(anzahlInput.toString());
}catch (NumberFormatException nfe){}
hinzufuegen_button = findViewById(R.id.zutat_hinzufuegen_button2);
zutatenView =(ListView) findViewById(R.id.zutatenliste2);
zutatenliste= new ArrayList<>();
zutatenadapter = new ArrayAdapter<String>(this,R.layout.zutatenliste_items,R.id.textitemliste,zutatenliste);
// zutatenadapter = new ArrayAdapter<String>(getApplicationContext(),android.R.layout.simple_spinner_item, zutatenliste);
zutatenView.setAdapter(zutatenadapter);
hinzufuegen_button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// hinzufuegen(v , einheiten_spinner);
ZutatClass newzutat = new ZutatClass(zutatInput.toString(),anzahlint,einheitInput);
zutatenliste.add((String) newzutat.zutat_sting);
zutatenadapter.notifyDataSetChanged();
}
});
}
}
This is what I see when i press the button a few times
I'm new to Android Studio and java so I hope it's not to much of a mess.
Thanks in advance.
First of all, you need to add Edittext inside the TextInputLayout and then get a text like this ZutatClass newzutat = new ZutatClass(zutatInput.getEditText().getText().toString(),anzahlint,einheitInput); on your on click method
I guess the issue is that you are trying to convert a TextInputLayout to string instead of getting the text from it and convert it to string , try the code below
hinzufuegen_button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// hinzufuegen(v , einheiten_spinner);
ZutatClass newzutat = new ZutatClass(zutatInput.getEditText().getText().toString(),anzahlintgetEditText().g etText().toString()
,einheitInput);
zutatenliste.add((String) newzutat.zutat_sting);
zutatenadapter.notifyDataSetChanged();
}
});
zutatInput.toString() --> zutatInput.getEditText().getText()
anzahlint.toString() --> anzahlint.getEditText().getText().toString()

ListView only show 1 item from Array

so lets just to the point, here is my code, and when i try to use Edittext and an button for saving data to listView, it works fine and all item show up on list view, but with a way that looks like in below, its only show one...
public class History extends Activity {
ListView show;
Button Home, toMap, Next;
EditText listTextMaker;
ArrayList<String> addArray = new ArrayList<String>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_history);
Home = findViewById(R.id.homeBtn);
toMap = findViewById(R.id.backBtn);
Next = findViewById(R.id.nextBtn);
show = findViewById(R.id.textHistory);
listTextMaker = findViewById(R.id.text);
listTextMaker.setVisibility(View.INVISIBLE);
ConstructorBuilder();
}
public void Constructor(){
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
String dataHistory = prefs.getString("History", null );
addArray.add(dataHistory);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(History.this, android.R.layout.simple_expandable_list_item_1, addArray);
show.setAdapter(adapter);
}
public void ConstructorBuilder(){
Constractor();
}
}
you are adding only one data on your list:
String dataHistory = prefs.getString("History", null );
addArray.add(dataHistory);
If you want more than one data then just use below code:
String dataHistory = prefs.getString("History", null );
addArray.add(dataHistory);
addArray.add(dataHistory);
addArray.add(dataHistory);
addArray.add(dataHistory);
addArray.add(dataHistory);

passing data from custom adapter to another activity

I have a listview which consist of items with prices. My listview also has a Delete button. I also have a textview at the bottom part of the layout which is not part of the listview and it shows the total amount. I can successfully remove the item from my listview. What I want is that when the item is removed, the total amount will also change.
Here is a part of my adapter where i must do some actions
holder.del.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
remove(getItem(position));
}
});
and here is my Activity where my textview of amount is found.
public class Cart extends MainActivity {
TextView amount_total;
ListView cartList;
CartCustomAdapter cartCustomAdapter;
String name, price;
static ArrayList<Order> cartArray = new ArrayList<Order>();
static Double total_amount = 0.00d;
static Double temp = 0.00d;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_cart);
amount_total = (TextView) findViewById(R.id.total_tv);
Bundle bundle = getIntent().getExtras();
Button checkout = (Button) findViewById(R.id.check_out);
Button add_item = (Button) findViewById(R.id.add_item);
name = bundle.getString("i_name");
price = bundle.getString("i_price");
temp = Double.parseDouble(price);
total_amount = (total_amount + temp);
amount_total.setText("Php" + total_amount.toString());
add_item.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(Cart.this,MainActivity.class);
startActivity(intent);
}
});
cartList = (ListView) findViewById(R.id.cart_list);
cartCustomAdapter = new CartCustomAdapter(Cart.this,R.layout.list_cart,cartArray);
cartList.setItemsCanFocus(false);
cartList.setAdapter(cartCustomAdapter);
cartArray.add(new Order(name,price,"1"));
cartCustomAdapter.notifyDataSetChanged();
}
}
Define an interface with method like below to update text view in your activity :
updateDeletedItemCount();
and in this method take integer and increase its count like
deletedCount++;
and then update it on text view like this
tvDeletedCount.setText("Deleted Item Count : "+ deletedCount);
This is the easiest way to do that:
//Add a method to your Cart
public void changeTotal(int totalPrice){
if(textView != null) // set total price
}
// Call after remove an item in your listener:
if(getContext() instanceOf Cart){
((Cart)getContext()).changeTotal(newTotalPrice);
}
This is not the best way, but I think it's ok for now :)

get user inputs from an editText and populate listView

How can i get user inputs from one activity and populate the listView with user data in another activity. I am able to get user input and populate the listView in the same activity. but now i want to get user inputs in one form and populate the list in another activity.
the code that i used to populate the listView by getting user input is as follows
public class MainActivity extends ListActivity {
ArrayList<String> list = new ArrayList<String>();
/** Declaring an ArrayAdapter to set items to ListView */
ArrayAdapter<String> adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button btn = (Button) findViewById(R.id.btnAdd);
/** Defining the ArrayAdapter to set items to ListView */
adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, list);
/** Defining a click event listener for the button "Add" */
View.OnClickListener listener = new View.OnClickListener() {
#Override
public void onClick(View v) {
EditText edit = (EditText) findViewById(R.id.txtItem);
String name=edit.getText().toString();
list.add(name);
edit.setText("");
adapter.notifyDataSetChanged();
}
};
/** Setting the event listener for the add button */
btn.setOnClickListener(listener);
you can store your user input / data into a local database; that will allow you to access your data anywhere in the app
(recommended since you are dealing with listview).
you can use shared preferences to store data if your data is relatively small.
In your current Activity (activity contains your button), create a new Intent:
String name = "";
name = edit.getText().toString();
Intent i = new Intent(getApplicationContext(), NewActivity.class);
i.putExtra("keyword",name);
startActivity(i);
Then in the NewActivity (activity contains your Listview), retrieve those values:
Bundle extras = getIntent().getExtras();
if (extras != null) {
String name = extras.getString("keyword");
if(name != ""){
// adapter.notifyDataSetChanged();
}
}
It is simple way, hope this help
Declare a public method in second Activity like
SecondActivity.class
public static ArrayList<String> list = new ArrayList<String>();
/** Declaring an ArrayAdapter to set items to ListView */
ArrayAdapter<String> adapter
onCreate()
{
...
;
adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, list);
listview.setAdapter(adapter);
...
}
public static void ModifyList()
{
adapter.notifyDataSetChanged();
}
FirstActivity.class
View.OnClickListener listener = new View.OnClickListener() {
#Override
public void onClick(View v) {
EditText edit = (EditText) findViewById(R.id.txtItem);
String name=edit.getText().toString();
SecondActivity.list.add(name);
edit.setText("");
SecondActivity.ModifyList();
}
};
Send your ArrayList like this from FirstActivity :
Intent intent = new Intent(FirstActivity.this, SecondActivity.class);
intent.putStringArrayListExtra("Datalist",list);
startActivity(intent);
In secondActivity Recieve the list using :
Intent i = getIntent();
list = i.getStringArrayListExtra("Datalist");
Then display it in your SecondActivitys listview

how to display path in our next activity on itemselect in listview

public class Lucenconcept extends Activity {
Button btn1;
EditText mEdit;
String txt2;
public ListAdapter adapter;
private ListView lv;
#Override
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
setContentView(R.layout.main);
File index = new File("/sdcard/index/");
index.mkdir();
mEdit = (EditText)findViewById(R.id.editText1);
lv=(ListView) findViewById(android.R.id.list);
btn1 = (Button)findViewById(R.id.button1);
btn1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Analyzer analyzer = new StandardAnalyzer();
IndexSearcher indexSearcher;
try {
indexSearcher = new IndexSearcher("/sdcard/index/");
QueryParser parser = new QueryParser("text", analyzer);
Hits hits = indexSearcher.search( parser.parse("("+ "text:" +mEdit.getText().toString() + ")"));
String txt2[] =new String[100];
String txt="";
for (int i = 0; i < hits.length(); i++) {
Document hitDoc = hits.doc(i);
Log.i("TestAndroidLuceneActivity", "Lucene: " +hitDoc.get("title")+ hitDoc.get("path"));
txt=hitDoc.get("title");
txt2[i]=txt;
String location=hitDoc.get("path");
}
lv.setAdapter(new ArrayAdapter
<String>
(Lucenconcept.this,android.R.layout.simple_list_item_1 ,txt2));
indexSearcher.close();
}
});
}
}
I m able show title on list view I want to display path hitDoc.get("path") from this string on item selct in next activity ..
Cud any one plz help meam not able to display url in next activty while I have put all the think manifest and all the I think there is mistake in postion plz help me..
Use Intent for passing data between activities
Refer Intent example

Categories

Resources