How can I getObjectId via onItemClick on ListView - android

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

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

Send data to new activity from listview JSON from mysql

I use bundle before but it only return null,
how can i get the name of the student_name that populated from database using json of the clicked item and show it into new activity?
public void ListDrawer() {
final List<Map<String, String>> studentList = new ArrayList<Map<String, String>>();
try {
JSONObject jsonResponse = new JSONObject(jsonResult);
JSONArray jsonMainNode = jsonResponse.optJSONArray("student_info");
for (int i = 0; i < jsonMainNode.length(); i++) {
JSONObject jsonChildNode = jsonMainNode.getJSONObject(i);
String name = jsonChildNode.optString("student_name");
String number = jsonChildNode.optString("student_id");
String outPut = name + "-" + number;
studentList.add(createStudent("Students", outPut));
}
} catch (JSONException e) {
Toast.makeText(getApplicationContext(), "Error" + e.toString(),
Toast.LENGTH_SHORT).show();
}
////////////////////////////////// UPDATE LISTVIEW ITEMS ONCLICK
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
//Do your logic for getting the student variables here
Intent intent = new Intent(MainPage.this,Profile.class);
intent.putExtra("student ", String.valueOf(id));
startActivity(intent);
}
});
//////////////////////////////////////UPDATE
SimpleAdapter simpleAdapter = new SimpleAdapter(this, studentList,
android.R.layout.simple_list_item_1,
new String[] { "Students" }, new int[] { android.R.id.text1 });
listView.setAdapter(simpleAdapter);
Toast.makeText(getApplication(), "Logged in Successfully", Toast.LENGTH_SHORT).show();
Above is mylistview and my onItemClicked function
i use json to retrieve the list of students from mysql and view it in listview and now im trying to pass data from the selected student in listview to new activity
[1]: http://i.stack.imgur.com/zc56O.jpg
To add on #brahmyadigopula comment, using POJO is way more simpler and if you are already using JSON as preferd way, you can use Googles library for transforming JSON strings in to Objects with one line of code.
https://github.com/google/gson
Then you can just transform the object into JSON String with the same library and pass it through the Intent as String and 'catch' it in the Activity as a string and transform it back to an Object and use it as you'd wish.
It would look something like this:
public class User {
private String name;
private String number;
(getters/setters)
}
And then in your adapter you would do:
User user = new Gson().fromJson(jsonMainNode, User.class);
so you can then have a cleaner code when getting the data. So when passing the data with an intent you can just transform the User object to string by doing this: String jsonString = new Gson().toJson(user); and pass it through the intent.
Hope this helps.
For your adapter, you're using "android.R.layout.simple_list_item_1" as a layout for your list items. This will give you a simple TextView as a result and this TextView will contain the whole student information (name-number) as a full String variable.
I have 3 solutions for your problem :
1- Get the text of the item TextView and use split function to get the students info as follows :
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
//Get the item full text content
String studentInfo = listView.getItemAtPosition(position).toString();
//Split using the space " "
ArrayList<String> studentInfoArray = new ArrayList<>(Arrays.asList(studentInfo.split(" ")));
//Split using the dash "-"
String lastObject = studentInfoArray.get(studentInfoArray.size() - 1);
ArrayList<String> lastObjectInfoArray = new ArrayList<>(Arrays.asList(lastObject.split("-")));
//Rearrange the student name
//Sometimes the name is composed of more than two words
String studentName = "";
for (int i = 0; i < studentInfoArray.size() - 1; i++) {
studentName += " " + studentInfoArray.get(i);
}
studentName += " " + lastObjectInfoArray.get(0);
//Create the intent to start the Profile activity
//Add student info to extras
Intent intent = new Intent(MainPage.this,Profile.class);
intent.putExtra("studentName", studentName);
intent.putExtra("studentID", lastObjectInfoArray.get(lastObjectInfoArray.size() - 1));
startActivity(intent);
}
});
2- Create a custom layout for your ListView adapter that will contain 2 TextViews in a LinearLayout, One for the name and One for the number. Then, you can easily get each info separately like this :
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
//Get the list item subviews using IDs of the custom item layout
TextView tvStudentName = (TextView)view.findViewById(R.id.tvStudentName);
TextView tvStudentNumber = (TextView)view.findViewById(R.id.tvStudentNumber);
//Create the intent to start the Profile activity
//Add student info to extras
Intent intent = new Intent(MainPage.this,Profile.class);
intent.putExtra("studentName", tvStudentName.getText());
intent.putExtra("studentID", tvStudentNumber.getText());
startActivity(intent);
}
});
3- Make your student list as a global variable, then just get the info directly from the array :
public class MainPage extends Activity {
//Declare studentList as a global variable
List<Map<String, String>> studentList = new ArrayList<>();
.
.
.
//Change the structure of your ListDrawer method
public void ListDrawer() {
try {
JSONObject jsonResponse = new JSONObject(jsonResult);
JSONArray jsonMainNode = jsonResponse.optJSONArray("student_info");
for (int i = 0; i < jsonMainNode.length(); i++) {
JSONObject jsonChildNode = jsonMainNode.getJSONObject(i);
String name = jsonChildNode.optString("student_name");
String number = jsonChildNode.optString("student_id");
//Add the student info to a new Hashmap object
//Add the student to the array
Map<String, String> studentInfo = new HashMap<>();
studentInfo.put("student_name", name);
studentInfo.put("student_id", number);
studentList.add(i, studentInfo);
}
} catch (JSONException e) {
Toast.makeText(getApplicationContext(), "Error" + e.toString(),
Toast.LENGTH_SHORT).show();
}
}
}
Then, send data to Profile activity :
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
//Create the intent to start the Profile activity
//Add student info to extras
Intent intent = new Intent(MainPage.this,Profile.class);
intent.putExtra("studentName", studentList.get(position).get("student_name"));
intent.putExtra("studentID", studentList.get(position).get("student_id"));
startActivity(intent);
}
});
Finally, to retrieve the info sent from MainPage Activity to Profile Activity :
public class Profile extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
.
.
Log.e("EXTRA", "Student Name : " + getIntent().getExtras().getString("studentName"));
Log.e("EXTRA", "Student ID : " + getIntent().getExtras().getString("studentID"));
}
}

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

listview - my new inserted data is replacing earlier data

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.

Categories

Resources