How to Partially removed JSON use intent putExtra on android - 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);

Related

How to pass json data in another activity [duplicate]

This question already has answers here:
Passing JSONObject into another activity
(7 answers)
Closed 6 years ago.
public class MainActivity extends **strong text**
AppCompatActivity {
private String TAG = MainActivity.class.getSimpleName();
private ListView lv;
ArrayList<HashMap<String, String>> companyList;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
companyList = new ArrayList<>();
lv = (ListView) findViewById(R.id.list_row_xml);
new GetCompany().execute();
lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int position, long id) {
Intent i = new Intent(MainActivity.this, SingleView.class);
i.putExtra("venue", venue);
startActivity(i);
}
});
}
private class GetCompany extends AsyncTask<Void, Void, JSONObject> {
#Override
protected void onPreExecute() {
super.onPreExecute();
Toast.makeText(MainActivity.this,"Json Data is downloading",Toast.LENGTH_LONG).show();
}
#RequiresApi(api = Build.VERSION_CODES.KITKAT)
#Override
protected JSONObject doInBackground(Void... arg0) {
HttpHandler sh = new HttpHandler();
// Making a request to url and getting response
String url = "http://10.0.2.2:6060/api/v1/company/getInfo?limit=10&page=1";
JSONArray company = sh.makeServiceCall(url);
Log.e(TAG, "Response from url: " + company);
if (company != null) {
try {
// JSONObject jsonObj = new JSONObject(jsonStr);
// Getting JSON Array node
//JSONArray company = new JSONArray(jsonStr);
// System.out.println("Reached");
// looping through All Contacts
for (int i = 0; i < company.length(); i++) {
//System.out.println("Reached1");
JSONObject c = company.getJSONObject(i);
String id = c.getString("id");
String name = c.getString("companyName");
// Walking Details in Json object
JSONObject walkingDetails=c.getJSONObject("walkingdetails");
String date = walkingDetails.getString("walkingdate");
String venue = walkingDetails.getString("venu");
// tmp hash map for single contact
HashMap<String, String> companyy = new HashMap<>();
// adding each child node to HashMap key => value
companyy.put("id",id);
companyy.put("date", date);
companyy.put("companyname", name);
companyy.put("venue", venue);
// adding contact to contact list
companyList.add(companyy);
}
} catch (final JSONException e) {
Log.e(TAG, "Json parsing error: " + e.getMessage());
runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(getApplicationContext(), "Json parsing error: " + e.getMessage(), Toast.LENGTH_LONG).show();
}
});
}
} else {
Log.e(TAG, "Couldn't get json from server.");
runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(getApplicationContext(), "Couldn't get json from server. Check LogCat for possible errors!", Toast.LENGTH_LONG).show();
}
});
}
return null;
}
/* #Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
ListAdapter adapter = new SimpleAdapter(MainActivity.this, companyList,
R.layout.list_row, new String[]{"date","companyname","venue"}, new int[]{ R.id.date, R.id.companyname, venue});
lv.setAdapter(adapter);*/
}
}
second acivity:
public class SingleView extends AppCompatActivity {
EditText txtVenue;
// String[] Venue;
int position;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_single_view);
Intent i = getIntent();
position = i.getExtras().getInt("positi`enter code here`on");
txtVenue = (EditText) findViewById(R.id.Venue);
}
}
You can not pass directly JSONObject to another activity. But you can convert json to string and pass it. Then in SecondActivity you can convert it to json again.
Start SecondActivity codes in FirstActivity:
Intent intent = new Intent(FirstActivity.this, SecondActivity.class);
intent.putExtra("data", json.toString());
startActivity(intent);
Then get this data from SecondActivity:
String data = getIntent().getStringExtra("data");
try {
JSONObject json = new JSONObject(data);
} catch (JSONException e) {
e.printStackTrace();
}
Good luck.
You can achieve by creating your own class by extending the JSONObject and implementing Serializable interface. So that you can pass through the intent.
You have 2 options:
1. Convert json to string and pass as string.
2. Make model class for json , make it parcelable. Pass this object to next activity.
HashMaps do not preserve ordering.
Better use a model class, it would also be easy to retrieve data.
public class CompanyData {
public String id;
public String date;
public String name;
public String venue;
}
then change arraylist,
ArrayList<CompanyData> companyList;
then store values,
CompanyData companyy = new CompanyData();
companyy.id = id;
companyy.date = date;
companyy.name = name;
companyy.venue = venue;
companyList.add(companyy);
then implement onitemclicklistener,
lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int position, long id) {
CompanyData data = companyList.get(position);
Intent i = new Intent(MainActivity.this, SingleView.class);
i.putExtra("venue", data.venue);
startActivity(i);
}
});
***To get position simply send position value inside onItemClickListener
lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int position, long id) {
CompanyData data = companyList.get(position);
Intent i = new Intent(MainActivity.this, SingleView.class);
i.putExtra("position", position);
startActivity(i);
}
});
You can also send all data of a specific position by
CompanyData data = companyList.get(position);
i.putExtra("data", data); //this will pass all data of clicked row

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 get one item from a listView after click listener

Please don't make it duplicate.
Hey everyone... I have asked this question before but nobody solve my problem. Here is my problem:
I want to perform the search action. In which data will be fetched from database and will be shown in listView. After clicking the one username it will pass his userID to second activity to show his Profile. The data include userID, username, gender, and address but only one item userID will be passed to second activity.
I have searched so many tutorials but found nothing like this.
I repeat again, please don't make it duplicate.
Here is my code:
listView.setAdapter(adapterSearchElements);
adapterSearchElements = new AdapterSearchElements(this, R.layout.searchresultcutomrow);
listView.setAdapter(adapterSearchElements);
json_string = getIntent().getExtras().getString("json_data");
try {
jsonObject = new JSONObject(json_string);
jsonArray = jsonObject.getJSONArray("server_response");
int count = 0;
for (int k = 0; k < jsonArray.length(); k++) {
// while (count < jsonArray.length()) {
// JSONObject JO = jsonArray.getJSONObject(count);
JSONObject JO = jsonArray.getJSONObject(Integer.parseInt(String.valueOf(k)));
user_id = JO.getString("user_id");
name = JO.getString("name");
Gender = JO.getString("Gender");
address = JO.getString("address");
final SearchResultsElements searchResultsElements = new SearchResultsElements(user_id,name, Gender, address);
adapterSearchElements.add(searchResultsElements);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// String userid=searchResultsElements.getUser_id();
// final String item = (String)parent.getItemIdAtPosition(position);
Intent i = new Intent(DisplaySearchResults.this, FriendsProfile.class);
i.putExtra("user_id", user_id);
startActivity(i);
}
});
// count++;
}
} catch (JSONException e) {
e.printStackTrace();
}
You only need to look up the SearchResultsElements at the position passed into the listView.setOnItemClickListener() callback like the following:
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
SearchResultsElements selectedSearchResultsElements = adapterSearchElements.getItem(position);
Intent i = new Intent(DisplaySearchResults.this, FriendsProfile.class);
i.putExtra("user_id", selectedSearchResultsElements.getUser_id());
startActivity(i);
}
});
I used the adapter here to look up the item. You can also use listView.getItemAtPosition(position); if you cast the returned object to the correct type.
If you get your elements from a database think of using CursorAdapter.

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