How to pass json data in another activity [duplicate] - android

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

Related

Get listview data while checked and pass it to another activity

Ive been searching for the right answer but nothing can solve my problems. I have a list view which is populated by my database from webserver. So basically what need is to get the data from the listview that is checked by user and pass the data to another activity. Sorry for my bad english hope you guys can help me.
Error ive received
E/AndroidRuntime: FATAL EXCEPTION: main
java.lang.IndexOutOfBoundsException: Invalid index 0, size is 0
at java.util.ArrayList.throwIndexOutOfBoundsException(ArrayList.java:251)
at java.util.ArrayList.get(ArrayList.java:304)
at firin.myuploads.Attendance$1.onClick(Attendance.java:74)
Attendance.java
public class Attendance extends AppCompatActivity {
//For Checkbox
ArrayList<String> selectedItems=new ArrayList<>();
private String TAG = MainActivity.class.getSimpleName();
private ProgressDialog pDialog;
private ListView lv;
private CheckBox cb;
private Button bGet;
//private id[] id;
private static String url = "www.myphpurl.com";
ArrayList<HashMap<String, String>> contactList;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_attendance);
contactList = new ArrayList<>();
bGet = (Button) findViewById(R.id.button7);
lv = (ListView) findViewById(R.id.list);
lv.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
new GetContacts().execute();
bGet.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
// String selected =((TextView)view.findViewById(R.id.mobile)).getText().toString();
CheckBox cb = (CheckBox) findViewById(R.id.cb);
cb.setChecked(true);
int len = lv.getCount();
SparseBooleanArray checked = lv.getCheckedItemPositions();
for (int i = 0; i < len; i++)
if (checked.get(i)) {
String item = selectedItems.get(i);
Toast.makeText(getApplicationContext(), item, Toast.LENGTH_LONG).show();
/*some code to save data in MainActivity*/
Intent in = new Intent(Attendance.this, SendMail.class);
in.putExtra("ListValue", item);
startActivity(in);}
}
});
}
This is the code where i populate my data to the listview
public class GetContacts extends AsyncTask<Void, Void, Void> {
#Override
protected Void doInBackground(Void... arg0) {
HttpHandler sh = new HttpHandler();
// Making a request to url and getting response
String jsonStr = sh.makeServiceCall(url);
Log.e(TAG, "Response from url: " + jsonStr);
if (jsonStr != null) {
try {
JSONObject jsonObj = new JSONObject(jsonStr);
// Getting JSON Array node
JSONArray result = jsonObj.getJSONArray("result");
// looping through All Contacts
for (int i = 0; i < result.length(); i++) {
JSONObject c = result.getJSONObject(i);
String id = c.getString("userID");
String studentName = c.getString("studentName");
String parentName = c.getString("parentName");
String parentEmail = c.getString("parentEmail");
// tmp hash map for single contact
HashMap<String, String> contact = new HashMap<>();
// adding each child node to HashMap key => value
contact.put("UID", id);
contact.put("sName", studentName);
contact.put("pName", parentName);
contact.put("pEmail", parentEmail);
// adding contact to contact list
contactList.add(contact);
}
} 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 onPreExecute() {
super.onPreExecute();
// Showing progress dialog
pDialog = new ProgressDialog(Attendance.this);
pDialog.setMessage("Please wait...");
pDialog.setCancelable(false);
pDialog.show();
}
#Override
public void onPostExecute(Void result) {
super.onPostExecute(result);
// Dismiss the progress dialog
if (pDialog.isShowing())
pDialog.dismiss();
/**
* Updating parsed JSON data into ListView
* */
ListAdapter adapter = new SimpleAdapter(
Attendance.this, contactList,
R.layout.list_item, new String[]{"sName", "pName",
"pEmail"}, new int[]{R.id.name,
R.id.email, R.id.mobile});
lv.setAdapter(adapter);
}
}
Is this how i set my setOnClick?
lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
String selected =((TextView)findViewById(R.id.mobile)).getText().toString();
CheckBox cb = (CheckBox) findViewById(R.id.cb);
cb.setChecked(true);
}});
Hope you guys can help me. thanks in advance
First you need to get how many item is selected in the listview, then after store in another array and pass that array to another activity.
Set you listview selection mode as Multi Choice.
listview.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
Set Listener on listview as below
ArrayList<String> selectedItem = new ArrayList();
listview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
view.setSelected(true);
adapter.getView(position, view, parent).setBackgroundColor(getResources().getColor(R.color.btn_login));
adapter.notifyDataSetChanged();
Log.i(TAG, "Selected Item is " + stateList.get(position));
selectedItem.add(yourArray.get(position))
}
});
you can invok your intent and pass selectedItem to that intent like this
Intent intent = new Intent(activity, YourActivity.class);
intent.putStringArrayListExtra("selected_list", selectedItem);
startActivity(intent);
and In your receiving intent you need to do:
ArrayList<String> selectedItem;
Intent i = getIntent();
selectedItem = i.getStringArrayListExtra("selected_list");

Get specific json object from listview click

I have my class that is based on a tutorial online, i dont fully understand it yet ( working on it ), but its working.
It populates the listview, now i want to get the id and show the data related to that id on a more detailed activity.
I already obtain the id of the item i am clicking:
list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View view, int position,
long id) {
Log.e("item clicks", "selected: " + position);
}
});
But now, i am not getting how i will do this, get the data of the position i clicked.
I have a inner class "GetObras" but i cant use the variables from it on my onCreate, i tried make them global, etc
public class MainActivity extends ActionBarActivity implements SearchView.OnQueryTextListener{
private String TAG = MainActivity.class.getSimpleName();
private ProgressDialog pDialog;
private ListView list;
private static String url = "http://ploran.gear.host/scriptobras6.php";
ArrayList<HashMap<String, String>> obrasList;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
obrasList = new ArrayList<HashMap<String, String>>();
list = (ListView)findViewById(R.id.list1);
new GetObras().execute();
list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View view, int position,
long id) {
Log.e("item clicks", "selected: " + position);
}
});
}
private class GetObras extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
// Showing progress dialog
pDialog = new ProgressDialog(MainActivity.this);
pDialog.setMessage("Please wait...");
pDialog.setCancelable(false);
pDialog.show();
}
#Override
protected Void doInBackground(Void... arg0) {
HttpHandler sh = new HttpHandler();
// Making a request to url and getting response
String jsonStr = sh.makeServiceCall(url);
Log.e(TAG, "Response from url: " + jsonStr);
if (jsonStr != null) {
try {
//JSONObject jsonObj = new JSONObject(jsonStr);
JSONArray obras = new JSONArray(jsonStr);
// Getting JSON Array node
//JSONArray obras = jsonObj.getJSONArray("obras");
// looping through All
for (int i = 0; i < obras.length(); i++) {
JSONObject c = obras.getJSONObject(i);
String id = c.getString("Id");
String nomeObra = c.getString("NomeObra");
String idCliente = c.getString("idCliente");
String DataLevantamento = c.getString("DataPLevantamento");
String DataRealizacao = c.getString("DataRLevantamento");
String Estado = c.getString("Estado");
String DataMateriais = c.getString("DataRMateriais");
String DataInicioObra = c.getString("DataInicioObra");
String DataConclusao = c.getString("DataConclusao");
String DataVestoria = c.getString("DataVestoria");
String Obs = c.getString("Obs");
String Prompor = c.getString("Prompor");
String Levantpor = c.getString("Levantpor");
String executpor = c.getString("executpor");
// tmp hash map for single contact
HashMap<String, String> obra = new HashMap<>();
// adding each child node to HashMap key => value
obra.put("Id", id);
obra.put("nomeObra", nomeObra);
obra.put("idCliente", idCliente);
obra.put("DataLevantamento", DataLevantamento);
obra.put("DataRealizacao", DataRealizacao);
obra.put("Estado", Estado);
obra.put("DataMateriais", DataMateriais);
obra.put("DataIncioObra", DataInicioObra);
obra.put("DataConclusao", DataConclusao);
obra.put("DataVestoria", DataVestoria);
obra.put("Obs", Obs);
obra.put("Prompor", Prompor);
obra.put("Levantpor", Levantpor);
obra.put("executpor", executpor);
// adding contact to contact list
obrasList.add(obra);
}
} 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);
// Dismiss the progress dialog
if (pDialog.isShowing())
pDialog.dismiss();
/**
* Updating parsed JSON data into ListView
* */
ListAdapter adapter = new SimpleAdapter(
MainActivity.this, obrasList,
R.layout.list_item, new String[]{"nomeObra", "idCliente",
"Estado"}, new int[]{R.id.name,
R.id.email, R.id.mobile});
list.setAdapter(adapter);
}
}
List<String> cities;
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_search, menu);
MenuItem searchItem = menu.findItem(R.id.search);
return true;
}
#Override
public boolean onQueryTextSubmit(String query) {
// User pressed the search button
return false;
}
#Override
public boolean onQueryTextChange(String newText) {
// User changed the text
return false;
}
}
If what i think is correct, i could just get the JsonArray from the doInBackground method in GetObras and do:
JSONObject c = obras.getJSONObject(position);
Thank you.
You can retrieve it using obrasList reference. As your are passing obrasList to your adapter.
Below is the sample code:
obrasList.get(position).get(yourkey);
Hope this will help you.. :))

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 extract integer value on textview to another integer inside listview onclicklistener

I working on an Android project which has a ListView and contains one TextView to display the contact and contact are stored in my website in form of json.
json link for contacts
I am able to parse the contacts I have no problem with that. But the problem is the parsed data is displayed as a number like "776057619" in the TextView and I want this TextView number to be taken and stored in a separate variable. By doing this I can use it to prompt the user "weather you want to call that particular number"??. But I don't no how to pull that number from the TextView to a separate variable and use to call inside ListView's OnItemClickListener
below is my code
public class Contactmedia extends ListActivity {
private ProgressDialog pDialog;
JSONParser jsonParser = new JSONParser();
private static final String READ_CONTACT_URL = "http://www.iamnotcrazy.hol.es/webservice/contact.php";
private static final String TAG_NUMBER ="number";
private static final String TAG_POSTS = "posts";
private JSONArray mid = null;
//manages all of our comments in a list.
private ArrayList<HashMap<String, String>> mContactList;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.contactmedialist);
}
#Override
protected void onResume() {
super.onResume();
new LoadComments().execute();
}
/**
* Retrieves json data of comments
*/
public void updateJSONdata() {
mContactList = new ArrayList<HashMap<String, String>>();
JSONParser jParser = new JSONParser();
JSONObject json = jParser.getJSONFromUrl(READ_CONTACT_URL);
try {
mid= json.getJSONArray(TAG_POSTS);
for (int i = 0; i < mid.length(); i++) {
JSONObject c = mid.getJSONObject(i);
String number = c.getString(TAG_NUMBER);
HashMap<String, String> map = new HashMap<String, String>();
map.put(TAG_NUMBER, number);
mContactList.add(map);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
/**
* Inserts the parsed data into our listview
*/
private void updateList() {
ListAdapter adapter = new SimpleAdapter(this, mContactList,
R.layout.contactmediadesign, new String[] { TAG_NUMBER
}, new int[] { R.id.contactno
});
setListAdapter(adapter);
ListView lv = getListView();
lv.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
/* this is where i have problem how to get that number without converting to string*/
TextView v = (TextView)view.findViewById(R.id.contactno);
int myNum = Integer.parseInt(v.getText().toString());
/* and here i want use that mynum after getiing phonenumber for calling purpouse ass shown below
* but its not working :(*/
if (position == 0){
Toast.makeText(getApplicationContext(), "yes you done it!!", Toast.LENGTH_SHORT).show();
Intent callIntent = new Intent(Intent.ACTION_CALL);
callIntent.setData(Uri.parse("tel:"+"myNum"));
startActivity(callIntent);
}
}
});
}
public class LoadComments extends AsyncTask<Void, Void, Boolean> {
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(Contactmedia.this);
pDialog.setMessage("Loading complaints...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
#Override
protected Boolean doInBackground(Void... arg0) {
updateJSONdata();
return null;
}
#Override
protected void onPostExecute(Boolean result) {
super.onPostExecute(result);
pDialog.dismiss();
updateList();
}
}
}
Since you actually need string, you don't have to convert to integer at all:
TextView v = (TextView)view.findViewById(R.id.contactno);
...
callIntent.setData(Uri.parse("tel:"+ v.getText().toString()));
or if you do need to store that number in variable for some reason, you should use String instead
TextView v = (TextView)view.findViewById(R.id.contactno);
string myNum = v.getText().toString();
...
callIntent.setData(Uri.parse("tel:" + myNum));
I would recommend getting the data associated with that position rather than trying to parse the view to get it.
You can get the data from the adapter with adapter.getItem(int pos). Just make adapter final or a member variable to access it in the OnItemClickListener.
First of all you should check your Manifest file, you should have this outside the "application" tag but within the "manifest" tag:
<uses-permission android:name="android.permission.CALL_PHONE" />
Try to do something like this in your code:
Intent callIntent = new Intent(Intent.ACTION_CALL, Uri.parse("tel:" + v.getText().toString()));
startActivity(callIntent);
You should use String value instead of int
remove the double quotation on mynum. you can also use basic oop to save your integer value. fyi, myNum doesnt have to be an integer. it can be a string
ListView lv = getListView();
lv.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
/* this is where i have problem how to get that number without converting to string*/
TextView v = (TextView)view.findViewById(R.id.contactno);
int myNum = Integer.parseInt(v.getText().toString());
setNumber(myNum); //saving the myNum variable
System.out.println("number is: " + getNumber());//if you want to get the value of myNum, just call the getNumber()
if (position == 0){
Toast.makeText(getApplicationContext(), "yes you done it!!", Toast.LENGTH_SHORT).show();
Intent callIntent = new Intent(Intent.ACTION_CALL);
callIntent.setData(Uri.parse("tel:"+ myNum));//remove the quotation for myNum
startActivity(callIntent);
}
}
private int number;
void setNumber(int number){
this.number=number;
}
int getNumber(){
return number;
}

json search bar in android appthat searches a json file from an api server

i want to have a search bar that searches a number that has been typed in (for example: 115048) and put that in a listview. the json file looks like this http://api.ccapp.it/v1/student/115048/schedule/11
hope someone can help me, the code that i use right now to search a link is like this but it doesnt have a search bar:
public class RoosterviewMd extends ListActivity {
Button mButton;
EditText mEdit;
private ProgressDialog pDialog;
// URL to get contacts JSON
//private static String id = null;
//private static String url = "http://api.ccapp.it/v1/student/" + id + "/schedule/11";
private static String url = "http://api.ccapp.it/v1/student/115048/schedule/12";
// JSON Node names
private static final String TAG_LESSON = "class";
private static final String TAG_ROOM = "room";
private static final String TAG_TEACHER = "teacher";
// contacts JSONArray
JSONArray contacts = null;
// Hashmap for ListView
ArrayList<HashMap<String, String>> contactList;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.roosterviewmd);
//Number input
final EditText input = (EditText) findViewById(R.id.editText2);
//buttons for all the days
Button btn2 = (Button) findViewById(R.id.button29);
btn2.setOnClickListener(new View.OnClickListener() {
public void onClick(View v)
{
Toast.makeText(getBaseContext(), "Je ziet je rooster voor maandag al" , Toast.LENGTH_SHORT ).show();
}
});
Button btnOne = (Button)findViewById(R.id.button30);
btnOne.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
Intent intent = new Intent(getApplicationContext(), RoosterviewDi.class);
startActivity(intent);
}
});
Button btnTwo = (Button)findViewById(R.id.button31);
btnTwo.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
Intent intent = new Intent(getApplicationContext(), RoosterviewWo.class);
startActivity(intent);
}
});
Button btnThree = (Button)findViewById(R.id.button32);
btnThree.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
Intent intent = new Intent(getApplicationContext(), RoosterviewDo.class);
startActivity(intent);
}
});
Button btnFour = (Button)findViewById(R.id.button33);
btnFour.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
Intent intent = new Intent(getApplicationContext(), RoosterviewVr.class);
startActivity(intent);
}
});
//Buttons end here
contactList = new ArrayList<HashMap<String, String>>();
ListView lv = getListView();
// Listview on item click listener
lv.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// getting values from selected ListItem
String lesson = ((TextView) view.findViewById(R.id.lesson))
.getText().toString();
String teacher = ((TextView) view.findViewById(R.id.teacher))
.getText().toString();
String room = ((TextView) view.findViewById(R.id.room))
.getText().toString();
}
});
// Calling async task to get json
new GetContacts().execute();
}
/**
* Async task class to get json by making HTTP call
* */
private class GetContacts extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
// Showing progress dialog
pDialog = new ProgressDialog(RoosterviewMd.this);
pDialog.setMessage("Give me a second please");
pDialog.setCancelable(false);
pDialog.show();
}
#Override
protected Void doInBackground(Void... arg0) {
// Creating service handler class instance
ServiceHandler sh = new ServiceHandler();
// Making a request to url and getting response
String jsonStr = sh.makeServiceCall(url, ServiceHandler.GET);
Log.d("Response: ", "> " + jsonStr);
if (jsonStr != null) {
try {
JSONObject jsonObj = new JSONObject(jsonStr);
JSONArray arr1 = jsonObj.getJSONArray("lessons");
JSONArray arr2 = arr1.getJSONArray(0); //Dag
for (int b = 0; b < arr2.length(); b++) {
JSONObject c = arr2.getJSONObject(b);
String lesson = c.getString(TAG_LESSON);
String teacher = c.getString(TAG_TEACHER);
String room = c.getString(TAG_ROOM);
// tmp hashmap for single contact
HashMap<String, String> contact = new HashMap<String, String>();
// adding each child node to HashMap key => value
contact.put(TAG_LESSON, lesson);
contact.put(TAG_TEACHER, teacher);
contact.put(TAG_ROOM, room);
// adding contact to contact list
contactList.add(contact);
}
} catch (JSONException e) {
e.printStackTrace();
}
} else {
Log.e("CCApp", "Couldn't get any data from the url");
Toast.makeText(getBaseContext(),"We are aware of this error and are working on it, in the mean time eat a cookie", Toast.LENGTH_LONG).show();
}
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
// Dismiss the progress dialog
if (pDialog.isShowing())
pDialog.dismiss();
/**
* Updating parsed JSON data into ListView
* */
ListAdapter adapter = new SimpleAdapter(RoosterviewMd.this, contactList,
R.layout.list_item, new String[] {TAG_LESSON, TAG_TEACHER,
TAG_ROOM }, new int[] { R.id.lesson,
R.id.teacher, R.id.room });
setListAdapter(adapter);
}
}
}
i hope someone can help me with this
Check out this answer: Get text from web page to string
Basically, you can simply get the text from the page and pass it into a string, and search the string application side for the contents of your edit text.
If you're looking for more functionality with the data from the web site, I would pull the Json into an array of Jsonobjects using something like Gson. You'd then be able to use the data from the web page in a bit more of a structured manner.
Edit: Now to actually answer your question.
You can include an edit text and button in your xml in order to search using a basic search bar kinda thing.
To set a listener on the button, you would do something like:
findViewById(R.id.button).setOnClickListener(new OnClickListener(){
#Override
protected void onClick(View v){
//Here, we can control what the response to the button press is, and grab the text in the edit text field.
String editTextString = findViewById(R.id.edittext).getEditableText().toString();
//Now we have a string used to parse the json or whatever else you need to do.
//May want to add a case here if editTextString is null to prevent runtime errors.
}
}
(Forgive me if there's any minor syntatic errors, just wrote that up quick here in the browser, no API to check on it. :))

Categories

Resources