listview - my new inserted data is replacing earlier data - android

I am beginner android developer and this is my first project. I have a listview on EntryTO.java to show data order from selected listview on ViewData.java. i use button to show ViewData,java. this is the code when i choose selected item from ViewData.java
ListView lv = (ListView) findViewById(android.R.id.list);
lv.setOnItemClickListener(new AdapterView.OnItemClickListener(){
#Override
public void onItemClick(final AdapterView<?> adapter, View v, int pos, final long id) {
final Dialog dialog = new Dialog(ViewData.this);
dialog.setContentView(R.layout.dialog_view);
dialog.setTitle("Masukkan Qty");
dialog.show();
final product b = (product) getListAdapter().getItem(pos);
edtqty = (EditText) dialog.findViewById(R.id.edtqty);
buttonok = (Button) dialog.findViewById(R.id.buttonok);
buttonok.setOnClickListener(new OnClickListener(){
#Override
public void onClick(View v) {
switchToEdit(b.getId());
dialog.dismiss();
};
});
}
});
}
public void switchToEdit(long id){
product b = dataSource.getproduct(id);
Intent i = new Intent(this, EntryTO.class);
Bundle bun = new Bundle();
bun.putLong("id", b.getId());
bun.putString("brand", b.getbrand());
bun.putString("qty",edtqty.getText().toString());
i.putExtras(bun);
finale();
startActivity(i);
}
And this is the code when i try to display on EntryTO.java
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.entry_to);
dataSource = new DBDataSource(this);
dataSource.open();
mylist = new ArrayList<HashMap<String, String>>();
Bundle bun = null;
try{
bun = EntryTO.this.getIntent().getExtras();
id = bun.getLong("id");
brand = bun.getString("brand");
qty = bun.getString("qty");
map1 = new HashMap<String, String>();
if(map1.isEmpty()){
map1.put("one", brand);
map1.put("two", qty);
mylist.add(map1);
}else{
int j=mylist.lastIndexOf(map1);
map1.put("one", brand);
map1.put("two", qty);
mylist.add(j,map1);
}
try {
adapter = new SimpleAdapter(EntryTO.this, mylist, R.layout.item_to,
new String[] {"one", "two" },
new int[] {R.id.edtbrandto, R.id.edtqtyto });
setListAdapter(adapter);
}catch (Exception e) {Toast.makeText(EntryTO.this, "Ada Error Exception", Toast.LENGTH_LONG).show();}
}catch(NullPointerException e){}}
I try to use loop before. When I insert first order there's no problem. But when I try to insert second order, the second replaced the first order. It caused when i click button that shown ViewData.java, index of arraylist become 0 again. Now I try to check index of arraylist(mylist) with if function. If mylist.isEmpty insert data order, but when mylist is not empty get the index of latest data order and insert new data after that. The problem is, second data still replaced first data. How do i fix them?

Choosing the approach you chose means you would need to store in your class the content you're passing to the ArrayAdapter implementation as the third parameter (i.e., the ArrayList of initial elements).
This way, if you need to add a new element, you just have to add it to that ArrayList and call notifyDataSetChanged() method.
For instance:
ArrayList<String> my_items = new ArrayList<String>();
my_items.add("one");
my_items.add("two");
adapter = new SimpleAdapter(EntryTO.this, mylist, R.layout.item_to, my_items);
And if you want to add an item, just do:
my_items.add("three");
adapter.dataSetChanged();
Hope this helps.

You are checking if(map1.isEmpty()) which is always true.
Use
if(mylist.size() == 0)
Instead of
if(map1.isEmpty())
and, to find out the next element going to be inserted, get the size which adds an item to the last position.
int j=mylist.size();

i found that answer from #ling.s was right. but it need some finishing touched. i try to make Globals.java. this is the code
public class Globals {
public static ArrayList<HashMap<String, String>> mylist;
}
on EntryTO.java we just call mylist from Globals.java
if (Globals.mylist == null)
Globals.mylist = new ArrayList<HashMap<String, String>>();
Bundle bun = null;
try{
bun = EntryTO.this.getIntent().getExtras();
id = bun.getLong("id");
brand = bun.getString("brand");
qty = bun.getString("qty");
map1 = new HashMap<String, String>();
if (Globals.mylist.size() == 0) {
map1.put("one", brand);
map1.put("two", qty);
Globals.mylist.add(map1);
}else {
int j=Globals.mylist.size();
map1.put("one", brand);
map1.put("two", qty);
Globals.mylist.add(j,map1);
}
try {
adapter = new SimpleAdapter(EntryTO.this, Globals.mylist, R.layout.item_to,
new String[] {"one", "two" },
new int[] {R.id.edtbrandto, R.id.edtqtyto });
setListAdapter(adapter);
}catch (Exception e) {Toast.makeText(EntryTO.this, "Ada Error Exception", Toast.LENGTH_LONG).show();}
}catch(NullPointerException e){}
its work.

Related

I've been trying to display the content of my database however I keep getting this error "java.lang.String cannot be cast to java.util.HashMap" [duplicate]

I like to pass selected item value from ListView to another activity.I am using City class with atributes idCity and nameCity and I like to pass the value of the city that is selected to another activity
This code is throwing java.lang.ClassCastException: java.lang.String cannot be cast to java.util.HashMap
public ListView cities;
ArrayList<City> cityList=new ArrayList<City>();
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.cities_view);
Resources r = getResources();
String[] c = r.getStringArray(R.array.cities);
for(int i=0;i<c.length;i++)
{
cityList.add(new City(i,c[i]));
}
for(int i=0;i<c.length;i++)
{
System.out.println(cityList.get(i).idCity);
System.out.println(cityList.get(i).nameCity);
}
cities = (ListView) findViewById(R.id.listCities);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1, c);
cities.setAdapter(adapter);
File file = new File(Environment.getExternalStorageDirectory()
.getAbsolutePath(), getString(R.string.exchangeOfficesFile));
if (!file.exists()) {
startService(new Intent(this, DownloadAsyncService.class));
}
try{
List<Map<String, String>> data = new ArrayList<Map<String, String>>();
for (City c : cityList) {
Map<String, String> map = new HashMap<String, String>(2);
map.put("idCity", Integer.toString(c.getIdCity()));
map.put("nameCity", c.getNameCity());
data.add(map);
}
cities.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
Intent intent = new Intent(getApplicationContext(),
CitiesDetails.class);
HashMap<String,String> map=(HashMap<String, String>) parent.getItemAtPosition(position);
intent.putExtra("idCity", map.get("idCity"));
intent.putExtra("nameCity", map.get("nameCity"));
startActivity(intent);
}
});
}catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
}
Maybe somebody had the same problem?
Your array adapter is a list of strings:
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, c);
getItemAtPosition(int position) will return an Object that matches the type of the Adapter. So in this case it will return a string, but you are trying to cast it to a HashMap<String, String>
HashMap<String,String> map=(HashMap<String, String>) parent.getItemAtPosition(position);
Change it to:
String result = (String) parent.getItemAtPosition(position);

How to Partially removed JSON use intent putExtra on android

recently , I use JSON parser
In my server showing text this.
[{"name":"AAA", "age":"111"},
{"name":"BBB", "age":"222"},
{"name":"CCC", "age":"333"}]
and I try JSON parser this text. show listview.
String strData = "";
.
.
.
#Override
protected void onPostExecute(final String result) {
super.onPostExecute(result);
final ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1);
try {
JSONArray jsonArray = new JSONArray(result);
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject object = jsonArray.getJSONObject(i);
data = object.getString("name") + "." + object.getString("age");
adapter.add(data);
}
} catch (JSONException e) {
e.printStackTrace();
}
ListView listView = (ListView) findViewById(R.id.listview);
listView.setAdapter(adapter);
}
and this result in my phone.
AAA.111
-------
BBB.222
-------
CCC.333
Until right here
but I want when I list item button click data transport.
so I use intent.putExtra
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
ListView listView =(ListView) parent;
Intent intent = new Intent(this, anotherActivity.class);
intent.putExtra("information", adapter.getItem(position));
startActivity(intent);
}
});
this is success data transport.
but I don't want all data transport.
for example . I send only age data trasport.
In other words , showing my phone name data, age data.
and transport another activity data. only name data.
is it possible programmatically?
if you not understand. please advice for me.
thanks.
#update question
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
ListView listView =(ListView) parent;
String data =adapter.getItem(position);
String[] parts = data.split(".");
String name = parts[0];
Log.d(TAG, name); // not showing log.. not work ?..
Intent intent = new Intent(this, anotherActivity.class);
intent.putExtra("information", adapter.getItem(position));
startActivity(intent);
}
});
Try this before declaring your intent
String data = adapter.getItem(position);
String[] parts = data.split(".");
String name = parts[0];
and then:
Intent intent = new Intent(this, anotherActivity.class);
intent.putExtra("information", name);
startActivity(intent);

ListView always has the same intent

I have a ListView that is updated from a ASyncTask, The adapter updates the list properly, however my setOnItemClickListener always has the same data in the intent.
This is the code for the loop that populates the ListView
if (JsonStr != null) {
//Get list of courses
JSONObject json = new JSONObject(JsonStr);
JSONObject Username = json.getJSONObject(InputUsername);
JSONObject Courses = Username.getJSONObject("Courses");
JSONObject CoursesItems = Courses.getJSONObject("items");
//Iterate around all courses
Iterator<String> i = CoursesItems.keys();
while (i.hasNext()) {
final String key = i.next();
JSONObject Course = (JSONObject) CoursesItems.get(key);
//Create a course entry
Map<String, String> ListEntry = new HashMap<>(2);
ListEntry.put("code", key);
if (Course.has("m_name")) {
String CourseName = (String) Course.get("m_name");
ListEntry.put("title", CourseName);
}
if (Course.has("original_source")) {
String Source = (String) Course.get("original_source");
ListEntry.put("source", Source);
}
JSONObject Units = null;
if (Course.has("Units")) {
Units = Course.getJSONObject("Units");
ListEntry.put("Units", Units.toString());
}
ListEntries.add(ListEntry);
final JSONObject finalUnits = Units;
runOnUiThread(new Runnable() {
public void run() {
SimpleAdapter adapter = new SimpleAdapter(
getApplicationContext(), //Activity
ListEntries, //List of pairs
R.layout.mymodules__list_item, //Target Parent Layout
new String[]{"title", "code", "source"}, //Key for pairs
new int[]{R.id.list_item_alert_textview,
R.id.list_item_date_textview,
R.id.list_item_source_textview}); //target items
ListView lv = (ListView) findViewById(R.id.listview);
lv.setAdapter(adapter);
lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Intent intent = new Intent(getApplicationContext(), CourseActivity.class);
intent.putExtra("Data", finalUnits.toString());
startActivity(intent);
}
});
}
});
}
}
'finalUnits' is final value .
move listener and data(List Units) to inside adapter.
and set listener in bindview method.
{
Intent i = new Intent(context,CourseActivity.class);
i.putExtra("Data",list.get(position).toString());
startActivity(i);
}
just replace by this code onitemclick
lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?>parent, View view, int position, long id) {
String value = (new ArrayList<String>(ListEntry.values())).get(position);
Intent intent = new Intent(getApplicationContext(), CourseActivity.class);
intent.putExtra("Data", value);
startActivity(intent);
}
});

how pass value of textview in custom listview when click on item to another activity? [duplicate]

This question already has answers here:
How to get value onListItemClick and pass it to another activity
(2 answers)
Closed 7 years ago.
i have a custom listview that fill from database and i want when click on any item value of textview pass to another activity, how should i do?
please help me!
this is all code , thanks u
source code:
Edit:
public class ListActivity extends Activity {
String value = "";
MovieDB myDbHelper;
SQLiteDatabase db;
ListAdapter adapter;
ArrayList<HashMap<String, String>> data;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.list_layout);
final ListView lst=(ListView) findViewById(R.id.listView1);
Load_Database();
db = myDbHelper.getReadableDatabase();
Cursor c = db.rawQuery("select * from movie_list where product = '"+value+"' Or name like '%"+value+"%'" , null);
data = new ArrayList<HashMap<String, String>>();
for (; c.moveToNext();) {
HashMap<String, String> map = new HashMap<String, String>();
String img = c.getString(c.getColumnIndex("img"));
String name = c.getString(c.getColumnIndex("name"));
map.put("img", img);
map.put("name", name);
data.add(map);
}
adapter = new ListMovie(this, data);
lst.setAdapter(adapter);
lst.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1,
int arg2, long arg3) {
final Intent GoToDisplay = new Intent(ListActivity.this,DisplayActivity.class);
GoToDisplay.putExtra("position", data.get(arg2));
startActivity(GoToDisplay);
}
});
}
private void Load_Database() throws Error {
myDbHelper = new MovieDB(ListActivity.this);
try {
myDbHelper.createDataBase();
} catch (IOException ioe) {
throw new Error("Unable to create database");
}
try {
myDbHelper.openDataBase();
} catch (SQLException sqle) {
throw sqle;
}
}
}
Step 1:
Just get data from adapter using position in ListView.
For. e.g.
You have ArrayList<String> data;//
then access like,
GoToDisplay.putExtra("position", data.get(arg2)); // as arg2 referees to clicked item position from ListView
Step 2:
Get Clicked TextView from View
TextView clickedTextView = (TextView)arg1.findViewById(// Id of your TextView); // Or get child from view arg1
GoToDisplay.putExtra("position", clickedTextView.getText().toString());
Note: As we don't know your Adapter data, above code is just example for understanding..

How can I getObjectId via onItemClick on ListView

I want use click listener to get ObjectId from parse.com,but the have something wrong I cant figure out. After Click item, getobjectId by click, and updating the new click Number to Parse.com
int ClickNum = (Integer) CN.get("ClickNumber");
Here have issues... Can you help me...
Toast and Log.d also not working here..
Thanks for your time
protected void onPostExecute(Void result) {
// Locate the listview in listview_main.xml
listview = (ListView) findViewById(R.id.listview);
// Pass the results into an ArrayAdapter
adapter = new ArrayAdapter<String>(MainActivity.this,
R.layout.listview_item);
int i=0;
ArrayList<String> GirlList= new ArrayList<String>();
String[] mStringArray ;
// Retrieve object "name" from Parse.com database
for (ParseObject AVgirl : ob) {
i++;
adapter.add(i+"."+(String) AVgirl.get("GirlName"));
// Log.d("123",(String) AVgirl.get("GirlName"));
//GirlList.add((String) AVgirl.get("GirlName"));
}
// Binds the Adapter to the ListView
listview.setAdapter(adapter);
// Close the progressdialog
mProgressDialog.dismiss();
// Capture button clicks on ListView items
listview.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
String Queen = parent.getItemAtPosition(position).toString();
ParseObject CN = new ParseObject(Queen);
int ClickNum = (Integer) CN.get("ClickNumber");
Toast.makeText(MainActivity.class,Queen,Toast.LENGTH_SHORT);
ClickNum++;
CN.put("ClickNumber", ClickNum);
Intent i = new Intent(MainActivity.this,
SingleItemView.class);
// Pass data "name" followed by the position
i.putExtra("name", ob.get(position).getString("GirlName")
.toString());
// Open SingleItemView.java Activity
startActivity(i);
}
});
Sorry, I cant upload here
logcat: http://i.imgur.com/dOjNLHl.png?1
updating, Yes, I figure out something during past 6 hour, and It's the code right now
// Send single item click data to SingleItemView Class
Intent i = new Intent(MainActivity.this,SingleItemView.class);
// Pass data "name" followed by the position
i.putExtra("name", ob.get(position).getString("GirlName")
.toString());
String girlname1 = "b";
Intent girlname = new Intent(MainActivity.this, SingleItemView.class);
girlname.putExtra(girlname1, ob.get(position).getString("GirlName")
.toString());
String ItemobjectId = "a";
Intent Plus1 = new Intent(MainActivity.this,SingleItemView.class);
Plus1.putExtra(ItemobjectId, ob.get(position).getString("ObjectId")
.toString());
System.out.println("點擊的是"+girlname1+"ObjectId ="+Plus1);
ParseObject CN = new ParseObject("AVGirlList");
String PlusAdd = Plus1.toString();
ParseQuery<ParseObject> query = ParseQuery.getQuery("AVGirlList");
query.getInBackground(PlusAdd, new GetCallback<ParseObject>() {
public void done(ParseObject object, ParseException e) {
if (e == null) {
int s = object.getInt("ClickNumber");
System.out.println(s);
s = s+1;
object.put("ClickNumber", s);
object.saveInBackground();
} else {
}
}
});
// Open SingleItemView.java Activity
startActivity(i);
}
});
and log cat is here
http://i.imgur.com/6p5ajXZ.png
//216 line:
Plus1.putExtra(ItemobjectId, ob.get(position).getString("ObjectId").toString());
It seem I cant use this method like that.
Please Help, Thanks

Categories

Resources