I want to get data from php, then show in listview. But I do not know not to tell the listview update the data I have got for php. I have try to use notifyDataSetChanged();, but I do know where should it put.
public class List_View extends ListFragment{
private String result;
private ListView listView;
private ArrayList<String> items = new ArrayList<String>();
final String uri = "http://localhost/userinfo.php";
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState){
View rootView = inflater.inflate(R.layout.list, container, false);
setListAdapter(new ArrayAdapter<String>(getActivity(), android.R.layout.simple_list_item_1, items));
return rootView;
}
class sendPostRunnable implements Runnable{
#Override
public void run(){
result = sendPostDataToInternet();
String temp = "Not result.";
try {
JSONTokener jsonTokener = new JSONTokener(result);
JSONObject jsonObject = (JSONObject) jsonTokener.nextValue();
JSONArray jarray = jsonObject.getJSONArray("response");
for (int i = 0; i < jarray.length(); i++) {
temp = "";
JSONObject jobject = jarray.getJSONObject(i);
temp += "name: "+jobject.getString("name")+"\n";
temp += "email: "+jobject.getString("email");
items.add(temp);
temp = "";
}
if(jarray.length() < 1){
items.add(temp);
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
private String sendPostDataToInternet(){
HttpPost httpRequest = new HttpPost(uri);
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("uid", "u1"));
try{
httpRequest.setEntity(new UrlEncodedFormEntity(params, HTTP.UTF_8));
HttpResponse httpResponse = new DefaultHttpClient().execute(httpRequest);
if (httpResponse.getStatusLine().getStatusCode() == 200){
String strResult = EntityUtils.toString(httpResponse.getEntity());
return strResult;
}
} catch (Exception e){
e.printStackTrace();
}
return null;
}
}
You should collect all arrived data in other collection (other than used in list adapter) in separate thread and then replace the list colletion source and right after than you should call notifyDataSetChanged().
public class List_View extends ListFragment{
private String result;
private ListView listView;
protected List newData;
protected ArrayAdapter listAdapter;
private ArrayList<String> items = new ArrayList<String>();
final String uri = "http://localhost/userinfo.php";
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState){
View rootView = inflater.inflate(R.layout.list, container, false);
listAdapter = new ArrayAdapter<String>(getActivity(), android.R.layout.simple_list_item_1, items);
setListAdapter(listAdapter );
return rootView;
}
class sendPostRunnable implements Runnable{
#Override
public void run(){
result = sendPostDataToInternet();
String temp = "Not result.";
// a new collection to fill from response
newData = new ArrayList<String>();
try {
JSONTokener jsonTokener = new JSONTokener(result);
JSONObject jsonObject = (JSONObject) jsonTokener.nextValue();
JSONArray jarray = jsonObject.getJSONArray("response");
for (int i = 0; i < jarray.length(); i++) {
temp = "";
JSONObject jobject = jarray.getJSONObject(i);
temp += "name: "+jobject.getString("name")+"\n";
temp += "email: "+jobject.getString("email");
//here you should create a corresponding object from JSON
// and add it to newData List
newData .add(temp);
temp = "";
}
if(jarray.length() < 1){
items.add(temp);
}
// here you will have a newData List filled so you should
// replace or add data from this List to ListView's used
items.add(newData);
listAdapter.notifyDataSetChanged();
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
private String sendPostDataToInternet(){
HttpPost httpRequest = new HttpPost(uri);
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("uid", "u1"));
try{
httpRequest.setEntity(new UrlEncodedFormEntity(params, HTTP.UTF_8));
HttpResponse httpResponse = new DefaultHttpClient().execute(httpRequest);
if (httpResponse.getStatusLine().getStatusCode() == 200){
String strResult = EntityUtils.toString(httpResponse.getEntity());
return strResult;
}
} catch (Exception e){
e.printStackTrace();
}
return null;
}
}
Related
How I can parse this json array?
{"1":
{"0":"3","id_disc":"3","1":"Дослідження і проектування компютерних систем","name":"Дослідження і проектування компютерних систем","2":"ДПКМС ","s_name":"ДПКМС "}
,"2":
{"0":"5","id_disc":"5","1":"Цивільний захист і охорона праці в галузі","name":"Цивільний захист і охорона праці в галузі","2":"ЦЗ і ОП","s_name":"ЦЗ і ОП"}
,"3":
{"0":"1","id_disc":"1","1":"Дослідження і проектування інтелектуальних систем (Лекція)","name":"Дослідження і проектування інтелектуальних систем (Лекція)","2":"ДіПІС","s_name":"ДіПІС"}
}
I was trying this method, but I always have null result.
String[] sA = new String[100];
try {
JSONArray cast = getDisc(paraaams).getJSONArray(" ");
for (int i=0; i<cast.length(); i++) {
JSONObject disc = cast.getJSONObject(i);
sA[i-1] = disc.getString("name");
}
}catch (JSONException e){}
// sA[0]=getDisc(paraaams).toString();
ArrayAdapter<String> adapter = new ArrayAdapter<>(getActivity(),
android.R.layout.simple_list_item_1, sA);
listView.setAdapter(adapter);
public JSONArray getDisc(Object params[]){
HTTPWorker httpWorker=new HTTPWorker();
JSONArray mjson =new JSONArray();
String s = httpWorker.doInBackground(params);
try {
mjson = new JSONArray(s);
Log.e("JSONinClass ",mjson.toString());
}catch (JSONException e){}
return mjson;
I think i try to parse it like json object, but i don't know how correct work with json arrays.
Thanks for help:)
my ListFragment:
public class MyFilesActivity extends android.app.Fragment {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.activity_myfiles, null);
ListView listView = (ListView) rootView.findViewById(R.id.listView);
String[] sA = new String[100];
JSONObject jsonObject = null;
try {
jsonObject = new JSONObject(getDisc(paraaams).toString());
} catch (JSONException e) {
e.printStackTrace();
}
int i =0;
Iterator<String> iterator = jsonObject.keys();
while (iterator.hasNext()) {
String key = iterator.next();
try {
if (jsonObject.has(key)) {
JSONObject value = jsonObject.getJSONObject(key);
// value is another JSONObject where you can get the "name" from
String name = value.getString("name");
sA[i]=name;
Log.e("value= ", name);
i+=1;
}
} catch (JSONException e) {
// Something went wrong!
e.printStackTrace();
}
}
// sA[0]=getDisc(paraaams).toString();
ArrayAdapter<String> adapter = new ArrayAdapter<>(getActivity(),
android.R.layout.simple_list_item_1, sA);
listView.setAdapter(adapter);
return rootView;
}
I cut it a bit, removed it is not important for the question :)
Try this for your Response to Parse
May Help you
try{
JSONObject jsonObject = new JSONObject(response);
List<String> keyList = getAllKeys(jsonObject);
for(String key : keyList){
JSONObject innerObject = jsonObject.getJSONObject(key);
List<String> innerKeyList = getAllKeys(innerObject);
for(String innerKey: innerKeyList){
System.out.println(innerObject.getString(innerKey));
}
}
}catch(Exception e){
e.printStackTrace();
}
This method will return keys
private List<String> getAllKeys(JSONObject jsonObject) throws JSONException{
List<String> keys = new ArrayList<String>();
Iterator<?> iterator = jsonObject.keys();
while( iterator.hasNext() ) {
String key = (String)iterator.next();
keys.add(key);
}
return keys;
}
try this:
please check below changes replace array to arraylist
public class MyFilesActivity extends android.app.Fragment {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.activity_myfiles, null);
ListView listView = (ListView) rootView.findViewById(R.id.listView);
ArrayList<String> sA = new ArrayList<>();
JSONObject jsonObject = null;
try {
jsonObject = new JSONObject(getDisc(paraaams).toString());
} catch (JSONException e) {
e.printStackTrace();
}
Iterator<String> iterator = jsonObject.keys();
while (iterator.hasNext()) {
String key = iterator.next();
try {
if (jsonObject.has(key)) {
JSONObject value = jsonObject.getJSONObject(key);
// value is another JSONObject where you can get the "name" from
String name = value.getString("name");
sA.add(name);
Log.e("value= ", name);
}
} catch (JSONException e) {
// Something went wrong!
e.printStackTrace();
}
}
// sA[0]=getDisc(paraaams).toString();
ArrayAdapter<String> adapter = new ArrayAdapter<>(getActivity(),
android.R.layout.simple_list_item_1, sA);
listView.setAdapter(adapter);
return rootView;
}
Here is a tested code to parse json.
try {
JSONObject json = new JSONObject(json);
int jsonLength = json.length();
for(int i=1; i<=jsonLength; i++){
JSONObject jObject = json.getJSONObject(""+i);
String data = jObject.getString("0");
}
} catch (JSONException e) {
e.printStackTrace();
}
It is just a plain JSONObject not an JSONArray, so you have to cast it to a JSONObject first
JSONObject json = new JSONObject(jsonString);
To loop through it
for (Iterator<String> iter = json.keys(); iter.hasNext();) {
String key = iter.next();
JSONObject value = (JSONObject) json.getJSONObject(key);
String name = value.getString("name");
}
I am trying to add items from database onto a listView, when I use System.out.println I see values but upon trying to populate them onto a custom listview returns no data in the listview.
When launching the app, I get a single row of listview item but of course it's empty.
public class MainActivity extends Activity implements AdapterView.OnItemClickListener {
String jsonResult;
String url = "http://www.mywebsite/query.php";
ListView list;
List<String> arrName;
List<String> arrNumber;
List<String> arrUsername;
List<String> arrStatus;
String name;
String number;
String username;
String status;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_contacts);
arrName = Arrays.asList(name);
arrNumber = Arrays.asList(number);
arrUsername = Arrays.asList(username);
arrStatus = Arrays.asList(status);
list = (ListView) findViewById(R.id.listContacts);
ConatctsAdapter adapter = new ConatctsAdapter(this, arrName, arrNumber, arrUsername, arrStatus);
list.setAdapter(adapter);
list.setOnItemClickListener(this);
accessWebService();
}
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int position, long id) { //SINGLE CLICK
// TODO Auto-generated method stub
}
// Async Task to access the web
private class JsonReadTask extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... params) {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(params[0]);
try {
HttpResponse response = httpclient.execute(httppost);
jsonResult = inputStreamToString(
response.getEntity().getContent()).toString();
}
catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
private StringBuilder inputStreamToString(InputStream is) {
String rLine = "";
StringBuilder answer = new StringBuilder();
BufferedReader rd = new BufferedReader(new InputStreamReader(is));
try {
while ((rLine = rd.readLine()) != null) {
answer.append(rLine);
}
}
catch (IOException e) {
// e.printStackTrace();
Toast.makeText(getApplicationContext(),
"Error..." + e.toString(), Toast.LENGTH_LONG).show();
}
return answer;
}
#Override
protected void onPostExecute(String result) {
ListDrwaer();
}
}// end async task
public void accessWebService() {
JsonReadTask task = new JsonReadTask();
// passes values for the urls string array
task.execute(new String[] { url });
}
// build hash set for list view
public void ListDrwaer() {
try {
JSONObject jsonResponse = new JSONObject(jsonResult);
JSONArray jsonMainNode = jsonResponse.optJSONArray("main");
for (int i = 0; i < jsonMainNode.length(); i++) {
JSONObject jsonChildNode = jsonMainNode.getJSONObject(i);
name = jsonChildNode.getString("Name");
number = jsonChildNode.getString("Number");
username = jsonChildNode.getString("Username");
status = jsonChildNode.getString("Status");
System.out.println("Name: "+name);
System.out.println("Number: "+number);
System.out.println("Username: "+username);
System.out.println("Status: "+status);
}
} catch (JSONException e) {
Log.i("Error Log: ", e.toString());
System.out.println("Error: "+e.toString());
Toast.makeText(getApplicationContext(), "Error" + e.toString(),
Toast.LENGTH_SHORT).show();
}
ContactsAdapter adapter = new ContactsAdapter(this, arrName, arrNumber, arrUsername, arrStatus);
list.setAdapter(adapter);
list.setOnItemClickListener(this);
}
class ContactsAdapter extends ArrayAdapter<String>
{
Context context;
List<String> Name;
List<String> Number;
List<String> Username;
List<String> Status;
ContactsAdapter(Context c, List<String> Name, List<String> Number, List<String> Username, List<String> Status)
{
super(c, R.layout.activity_contacts_single, R.id.textName, Name);
this.context=c;
this.Name=Name;
this.Number=Number;
this.Username=Username;
this.Status=Status;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
View row=convertView;
if(row==null)
{
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
row = inflater.inflate(R.layout.activity_contacts_single, parent, false);
}
TextView txtName = (TextView) row.findViewById(R.id.textName);
TextView txtNumber = (TextView) row.findViewById(R.id.textNumber);
TextView txtUsername = (TextView) row.findViewById(R.id.textUsername);
TextView txtStatus = (TextView) row.findViewById(R.id.textStatus);
txtName.setText(Name.get(position));
txtNumber.setText(Number.get(position));
txtUsername.setText(Username.get(position));
txtStatus.setText(Status.get(position));
return row;
}
}
}
It's because you haven't add those items into your lists, Change this part of your code:
try {
JSONObject jsonResponse = new JSONObject(jsonResult);
JSONArray jsonMainNode = jsonResponse.optJSONArray("main");
for (int i = 0; i < jsonMainNode.length(); i++) {
JSONObject jsonChildNode = jsonMainNode.getJSONObject(i);
name = jsonChildNode.getString("Name");
number = jsonChildNode.getString("Number");
username = jsonChildNode.getString("Username");
status = jsonChildNode.getString("Status");
//add this part to your code
arrName.add(name);
arrNumber.add(number);
arrUsername.add(username);
arrStatus.add(status);
System.out.println("Name: "+name);
System.out.println("Number: "+number);
System.out.println("Username: "+username);
System.out.println("Status: "+status);
}
} catch (JSONException e) {
Log.i("Error Log: ", e.toString());
System.out.println("Error: "+e.toString());
Toast.makeText(getApplicationContext(), "Error" + e.toString(),
Toast.LENGTH_SHORT).show();
}
ContactsAdapter adapter = new ContactsAdapter(this, arrName, arrNumber, arrUsername, arrStatus);
list.setAdapter(adapter);
list.setOnItemClickListener(this);
}
for your second problem I think you can change your code this way:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_contacts);
//arrName = Arrays.asList(name);
//arrNumber = Arrays.asList(number);
//arrUsername = Arrays.asList(username);
//arrStatus = Arrays.asList(status);
arrName = new ArrayList<String>();
arrNumber =new ArrayList<String>();
arrUsername =new ArrayList<String>();
arrStatus =new ArrayList<String>();
list = (ListView) findViewById(R.id.listContacts);
ConatctsAdapter adapter = new ConatctsAdapter(this, arrName, arrNumber, arrUsername, arrStatus);
list.setAdapter(adapter);
list.setOnItemClickListener(this);
accessWebService();
}
I have two fragments in site my first fragment call AsyncTask and get some json values.and then i want to pass my JSON values to my second Fragment's TextViews.What is the best way pass json value between fragments?
this is my AsyncTask in Fragment 1
class LoadingAccountEntry extends AsyncTask<String, String, String> {
#Override
protected void onPreExecute() {
}
#Override
protected String doInBackground(String... args) {
String response;
Map<String, Object> data = new LinkedHashMap<String, Object>();
data.put(SESSION, sessionId);
data.put(MODULE_NAME, module_name);
data.put(ID, entry_id != null ? entry_id : "");
data.put(
SELECT_FIELDS,
(selectFields != null && selectFields.length != 0) ? new JSONArray(
Arrays.asList(selectFields)) : "");
try {
JSONArray nameValueArray = new JSONArray();
if (linkNameToFieldsArray != null
&& linkNameToFieldsArray.size() != 0) {
for (Entry<String, List<String>> entry : linkNameToFieldsArray
.entrySet()) {
JSONObject nameValue = new JSONObject();
nameValue.put("name", entry.getKey());
nameValue.put("value", new JSONArray(entry.getValue()));
nameValueArray.put(nameValue);
}
}
data.put(LINK_NAME_TO_FIELDS_ARRAY, nameValueArray);
String restData = org.json.simple.JSONValue.toJSONString(data);
HttpClient httpClient = new DefaultHttpClient();
HttpPost req = new HttpPost(restURL);
// Add your data
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair(METHOD, GET_ENTRY));
nameValuePairs.add(new BasicNameValuePair(INPUT_TYPE, JSON));
nameValuePairs.add(new BasicNameValuePair(RESPONSE_TYPE, JSON));
nameValuePairs.add(new BasicNameValuePair(REST_DATA, restData));
req.setEntity(new UrlEncodedFormEntity(nameValuePairs));
// Send POST request
httpClient.getParams().setBooleanParameter(
CoreProtocolPNames.USE_EXPECT_CONTINUE, false);
HttpResponse res = httpClient.execute(req);
response = EntityUtils.toString(res.getEntity());
// Log.d("Responce", response.toString());
if (response == null) {
Log.e("Error !", "faild to connect !");
}
JSONObject responseObj = new JSONObject(response);
JSONArray jArray = responseObj.getJSONArray(ENTRY_LIST);
for (int i = 0; i < jArray.length(); i++) {
JSONObject obj = jArray.getJSONObject(i);
// Log.d("obj", obj.toString());
// JSONObject objName = new JSONObject("name");
id = obj.getString("id");
Log.d("id", id);
JSONObject name_value_list = obj
.getJSONObject("name_value_list");
JSONObject assignedUserName = name_value_list
.getJSONObject("assigned_user_name");
assigned_user_name = assignedUserName.getString("value");
Log.d("assigned_user_name", assigned_user_name);
JSONObject modifiedByName = name_value_list
.getJSONObject("modified_by_name");
modified_by_name = modifiedByName.getString("value");
Log.d("modified_by_name", modified_by_name);
}
} catch (JSONException e) {
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(String result) {
}
This Fragment 2
public class Fragment_account_details extends Fragment {
TextView name, officePhone,fax;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_account_details, container,false);
name = (TextView) rootView.findViewById(R.id.text_name);
fax = (TextView) rootView.findViewById(R.id.text_fax);
return rootView;
}
You can use bundle to pass data to Fragment_account_details like this :
Fragment fragment = new Fragment_account_details();
Bundle bundle = new Bundle();
bundle.putString("name", name);
fragment.setArguments(bundle);
now in your Fragment_account_details onCreateView do like :
String name= getArguments().getString("name");
like this you can pass values.hope this helps.
I'm trying to show a ListView, with my custom adapter in a Fragment, but it doesn't appear. I use the same code that I used in a normal activity and it worked but in this fragment no...
the code gives no error, but nothing appears.
public class Amics extends Fragment {
ListView listView_Amics;
ArrayAdapter<Usuari> adapter;
List<Usuari> list = new ArrayList<Usuari>();
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
View rootView = inflater.inflate(R.layout.amics, container, false);
listView_Amics = (ListView) rootView.findViewById(R.id.listView_amics);
adapter = new MyAdapter_Amics(getActivity(),list);
listView_Amics.setAdapter(adapter);
obtenir_amics1(); // THIS FUNCTION ADD ELEMENTS TO THE LIST AND SETS ADAPTER
return rootView;
}
public boolean obtenir_amics1(){
String data = null; // THE STRING TO SAVE HTTPOST RESPONSE
// HTTP POST DATA RECIEVING..
List<NameValuePair> parametres = new ArrayList<NameValuePair>();
parametres.add(new BasicNameValuePair("id", id));
try {
DefaultHttpClient client = new DefaultHttpClient();
HttpPost request = new HttpPost("MY_HOST");
request.setEntity(new UrlEncodedFormEntity(parametres));
HttpResponse response = client.execute(request);
HttpEntity entity = response.getEntity();
data = EntityUtils.toString(entity);
Log.e("DADES OBTINGUDES", data);
try {
JSONArray json = new JSONArray(data);
int limit = 50;
if(json.length()<limit){limit=json.length();}
for (int i = 0; i < limit; i++) {
JSONObject obj = json.getJSONObject(i);
String nombre = obj.getString("usuario_two");
boolean selected = false;
Log.e("amic:", nombre);
list.add(new Usuari(nombre,selected));
listView_Amics.setAdapter(adapter);
}
return true;
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} catch (ClientProtocolException e) {
Log.d("HTTPCLIENT", e.getLocalizedMessage());
} catch (IOException e) {
Log.d("HTTPCLIENT", e.getLocalizedMessage());
}
return false;
}
Override the onResume() method and shift adapter = new MyAdapter_Amics(getActivity(),list);
listView_Amics.setAdapter(adapter);
obtenir_amics1();to onResume().
I'm practising with some tutorials I found on the web, I am communicating with a database for a listing, the unfold in a listview listview adapter as show you various names, I would like to add a search dialog, something like this Example Image but no where in the deploy, I have tried in various ways.
this is part of the code example:
LIST ACTIVITY:
public class List extends Activity {
private ProgressDialog pDialog;
public int i = 0;
JSONParser jParser = new JSONParser();
ArrayList<HashMap<String, String>> DaftarRS = new ArrayList<HashMap<String, String>>();
private static String url_daftar_rs = "my_url";
public static final String TAG_SUCCESS = "success";
public static final String TAG_DAFTAR_RS = "daftar_rs";
public static final String TAG_ID_RS = "id_rs";
public static final String TAG_NAMA_RS = "nama_rs";
public static final String TAG_LINK_IMAGE_RS = "link_image_rs";
public static final String TAG_ALAMA_RS = "alamat_rs";
public static final String TAG_TELEPONS_RS = "telepon_rs";
JSONArray daftar_rs = null;
ListView list;
ListAdapter adapter;
private ListadoActivity activity;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.list);
DaftarRS = new ArrayList<HashMap<String, String>>();
new Activity().execute();
activity = this;
list = (ListView) findViewById(R.id.list);
list.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
String id_rs = ((TextView) view
.findViewById(R.id.id_rs)).getText().toString();
Intent in = new Intent(getApplicationContext(),
DetallesActivity.class);
in.putExtra(TAG_ID_RS, id_rs);
startActivityForResult(in, 100);
}
});
}
public void SetListViewAdapter(ArrayList<HashMap<String, String>> daftar) {
adapter = new ListAdapter(activity, daftar);
list.setAdapter(adapter);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == 100) {
Intent intent = getIntent();
finish();
startActivity(intent);
}
}
class Activity extends AsyncTask<String, String, String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(List.this);
pDialog.setMessage("wait..");
pDialog.setIndeterminate(false);
pDialog.setCancelable(false);
pDialog.show();
}
protected String doInBackground(String... args) {
Conexion();
if (i == 0) {
List<NameValuePair> params = new ArrayList<NameValuePair>();
JSONObject json = jParser.makeHttpRequest(url_daftar_rs, "GET",
params);
Log.d("All Products: ", json.toString());
try {
int success = json.getInt(TAG_SUCCESS);
if (success == 1) {
daftar_rs = json.getJSONArray(TAG_DAFTAR_RS);
for (int i = 0; i < daftar_rs.length(); i++) {
JSONObject c = daftar_rs.getJSONObject(i);
String id_rs = c.getString(TAG_ID_RS);
String nama_rs = c.getString(TAG_NAMA_RS);
String link_image_rs = c
.getString(TAG_LINK_IMAGE_RS);
String alamat_rs = c.getString(TAG_ALAMAT_RS);
String telepon_rs = c.getString(TAG_TELEPON_RS);
HashMap<String, String> map = new HashMap<String, String>();
map.put(TAG_ID_RS, id_rs);
map.put(TAG_NAMA_RS, nama_rs);
map.put(TAG_LINK_IMAGE_RS, link_image_rs);
map.put(TAG_ALAMAT_RS, alamat_rs);
map.put(TAG_TELEPON_RS, telepon_rs);
DaftarRS.add(map);
}
} else {
}
} catch (JSONException e) {
e.printStackTrace();
}
}
else{ finish();
}
return null;
}
JSON PARSER:
public class JSONParser {
static InputStream is = null;
static JSONObject jObj = null;
static String json = "";
public JSONParser() {
}
// function get json from url
// by making HTTP POST or GET method
public JSONObject makeHttpRequest(String url, String method,
List<NameValuePair> params) {
// Making HTTP request
try {
// check for request method
if (method == "POST") {
// request method is POST
// defaultHttpClient
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
httpPost.setEntity(new UrlEncodedFormEntity(params));
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
} else if (method == "GET") {
// request method is GET
DefaultHttpClient httpClient = new DefaultHttpClient();
String paramString = URLEncodedUtils.format(params, "utf-8");
url += "?" + paramString;
HttpGet httpGet = new HttpGet(url);
HttpResponse httpResponse = httpClient.execute(httpGet);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
}
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(
is, "iso-8859-1"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
json = sb.toString();
} catch (Exception e) {
Log.e("Buffer Error", "Error converting result " + e.toString());
}
// try parse the string to a JSON object
try {
jObj = new JSONObject(json);
} catch (JSONException e) {
Log.e("JSON Parser", "Error parsing data " + e.toString());
}
// return JSON String
return jObj;
}
}
LISTADAPTER:
public class ListAdapter extends BaseAdapter {
private Activity activity;
private ArrayList<HashMap<String, String>> data;
private static LayoutInflater inflater = null;
public ImageLoader imageLoader;
public ListAdapter(Activity a, ArrayList<HashMap<String, String>> d) {
activity = a;
data = d;
inflater = (LayoutInflater) activity
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
imageLoader = new ImageLoader(activity.getApplicationContext());
}
public int getCount() {
return data.size();
}
public Object getItem(int position) {
return position;
}
public long getItemId(int position) {
return position;
}
public View getView(int position, View convertView, ViewGroup parent) {
View vi = convertView;
if (convertView == null)
vi = inflater.inflate(R.layout.item_list_rs, null);
TextView id_rs = (TextView) vi.findViewById(R.id.id_rs);
TextView nama_rs = (TextView) vi.findViewById(R.id.nama_rs);
TextView link_image_rs = (TextView) vi.findViewById(R.id.link_image_rs);
TextView alamat_rs = (TextView) vi.findViewById(R.id.alamat_rs);
TextView telepon_rs = (TextView) vi.findViewById(R.id.telepon_rs);
ImageView thumb_image = (ImageView) vi.findViewById(R.id.image_rs);
HashMap<String, String> daftar_rs = new HashMap<String, String>();
daftar_rs = data.get(position);
id_rs.setText(daftar_rs.get(ListadoActivity.TAG_ID_RS));
nama_rs.setText(daftar_rs.get(ListadoActivity.TAG_NAMA_RS));
link_image_rs.setText(daftar_rs.get(ListadoActivity.TAG_LINK_IMAGE_RS));
alamat_rs.setText(daftar_rs.get(ListadoActivity.TAG_ALAMAT_RS));
telepon_rs.setText(daftar_rs.get(ListadoActivity.TAG_TELEPON_RS));
imageLoader.DisplayImage(daftar_rs.get(ListadoActivity.TAG_LINK_IMAGE_RS),
thumb_image);
return vi;
}
}
Why don't you add an EditText to the layout xml and pass the text as an argument after the List<NameValuePair> params = new ArrayList<NameValuePair>();
Something like:
params.add(new BasicNameValuePair(TAG_NAME, name));