I am new in android,I have created a simple listview which is fetching data from mysql and every thing is working fine but now i want to pass the values of listview(Row) to another activity and when i am clicking on particular row i am getting null value.
public class AdminNotice extends Activity {
private String[] navMenuTitles;
private TypedArray navMenuIcons;
private EditText editTextName;
SharedPreferences sp;
private String jsonResult;
private ListView listView;
private Button b;
EditText etname, et;
TextView tv;
String myJSON;
private static final String TAG = "MainActivity.java";
private static final String TAG_NAME = "notice";
private static final String TAG_DATE = "ndate";
ProgressBar progressBar;
Date date;
JSONArray peoples = null;
ArrayList<HashMap<String, String>> personList;
ListView list;
public static final String USER_NAME = "USERNAME";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.noticelist);
progressBar = (ProgressBar) findViewById(R.id.progressbar);
//SharedPreferences myprefs= getSharedPreferences("user", MODE_WORLD_READABLE);
// String session_id= myprefs.getString("session_id", null);
//TextView textView = (TextView) findViewById(R.id.fname);
//textView.setText("Welcome "+session_id);
navMenuTitles = getResources().getStringArray(R.array.nav_drawer_items);
navMenuIcons = getResources().obtainTypedArray(R.array.nav_drawer_icons);
// load icons from
// strings.xml
list = (ListView) findViewById(R.id.listView);
personList = new ArrayList<HashMap<String,String>>();
getData();
}
//send messages stop
//get json data start
protected void showList(){
try {
JSONArray peoples = new JSONArray(myJSON);
for(int i=0;i<peoples.length();i++){
JSONObject c = peoples.getJSONObject(i);
String name=null, date=null;
/*if(c==null){
ProgressDialog progress = new ProgressDialog(this);
progress.setTitle("Loading");
progress.setMessage("Wait while loading...");
progress.show();
}*/
if(c.has("notice"))
if(c.has("ndate"))
progressBar.setVisibility(View.GONE);
name = c.getString("notice");
date = c.getString("ndate");
list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
long arg3) {
HashMap<String, Object> data = (HashMap<String, Object>) arg0.getItemAtPosition(arg2);
Intent intent = new Intent(getApplicationContext(), SingleMessage.class);
intent.putExtra("KEY", data);
startActivity(intent);
}
});
HashMap<String,String> persons = new HashMap<String,String>();
persons.put(TAG_NAME,name);
persons.put(TAG_DATE,date);
personList.add(persons);
}
ListAdapter adapter = new SimpleAdapter(
AdminNotice.this, personList, R.layout.list_item1,
new String[]{TAG_NAME,TAG_DATE},
new int[]{R.id.name, R.id.date}
);
list.setAdapter(adapter);
/* list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView parent, View view, int position, long id) {
Toast.makeText(getApplicationContext(), ((TextView) view).getText(), Toast.LENGTH_SHORT).show();
}
});*/
} catch (JSONException e) {
Log.i("tagconvertstr", "["+myJSON+"]");
}
}
public void getData(){
class GetDataJSON extends AsyncTask<String, Void, String>{
#Override
protected String doInBackground(String... params) {
SharedPreferences myprefs= getSharedPreferences("user", MODE_WORLD_READABLE);
String session_id= myprefs.getString("session_id", null);
InputStream inputStream = null;
String result = null;
try {
String postReceiverUrl = "http://.php";
// HttpClient
HttpClient httpClient = new DefaultHttpClient();
// post header
HttpPost httpPost = new HttpPost(postReceiverUrl);
// add your data
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
nameValuePairs.add(new BasicNameValuePair("username", session_id));
httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpClient.execute(httpPost);
HttpEntity resEntity = response.getEntity();
inputStream = resEntity.getContent();
// json is UTF-8 by default
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null)
{
sb.append(line + "\n");
}
result = sb.toString();
} catch (Exception e) {
Log.i("tagconvertstr", "["+result+"]");
System.out.println(e);
}
finally {
try{if(inputStream != null)inputStream.close();}catch(Exception squish){}
}
return result;
}
#Override
protected void onPostExecute(String result){
myJSON = result;
showList();
}
}
GetDataJSON g = new GetDataJSON();
g.execute();
}
//get json data stop
}
set the OnItemClickListener to the list view
public boolean onItemClick(AdapterView<?> arg0, View arg1, int position, long arg3) {
/ /write your code here to send data like
ModelClass obj = getItem(position);
String name = obj.getName();
Intent intent = new Intent(Activity.this, Activity2.class);
intent.putExtras("Name", name);
startActivity(intent);
}
or you can do like this way also
interfaceObj.sendData(obj);
Related
I am developing an android app which functions like as follows
Admin creates the data and saves it into database then user access the same data through app when it comes down to showing the data to user i fetch the data from the database which admin has already saved i show the data in listview, and listview having buttons in each row when user click on button it dose not goes to next activity.When user will click on button in listview the activity should pass to next activity.How do i do this?
//java activity
public class MainActivity extends ActionBarActivity {
String myJSON;
SimpleAdapter adapter;
Button btn;
private static final String TAG_RESULTS = "result";
private static final String TAG_NAME = "sname";
private static final String TAG_PRICE = "sprice";
JSONArray peoples = null;
ArrayList<HashMap<String, String>> personList;
// ArrayList<HashMap<String, String>> personList = new ArrayList<HashMap<String, String>>();
ListView list, listView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
list = (ListView) findViewById(R.id.listView_search);
btn = (Button) findViewById(R.id.button3_book);
personList = new ArrayList<HashMap<String, String>>();
getData();
// Listview on item click listener
list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
Intent zoom=new Intent(parent.getContext(), Details.class);
parent.getContext().startActivity(zoom);
}
});
}
protected void showList(){
try {
JSONObject jsonObj = new JSONObject(myJSON);
peoples = jsonObj.getJSONArray(TAG_RESULTS);
for(int i=0;i<peoples.length();i++){
JSONObject c = peoples.getJSONObject(i);
String sname = c.getString(TAG_NAME);
String sprice = c.getString(TAG_PRICE);
HashMap<String,String> persons = new HashMap<String,String>();
persons.put(TAG_NAME,sname);
persons.put(TAG_PRICE,sprice);
personList.add(persons);
}
ListAdapter adapter = new SimpleAdapter(
MainActivity.this, personList, R.layout.search_item,
new String[]{TAG_NAME,TAG_PRICE},
new int[]{ R.id.textView8_sellernm, R.id.textView19_bprice}
);
list.setAdapter(adapter);
list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Intent i=new Intent(MainActivity.this,Details.class);
startActivity(i);
}
});
} catch (JSONException e) {
e.printStackTrace();
}
}
public void getData(){
class GetDataJSON extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... params) {
DefaultHttpClient httpclient = new DefaultHttpClient(new BasicHttpParams());
HttpPost httppost = new HttpPost("http://example.com/User/reg/listview.php");
// Depends on your web service
httppost.setHeader("Content-type", "application/json");
InputStream inputStream = null;
String result = null;
try {
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
inputStream = entity.getContent();
// json is UTF-8 by default
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null)
{
sb.append(line + "\n");
}
result = sb.toString();
} catch (Exception e) {
// Oops
}
finally {
try{if(inputStream != null)inputStream.close();}catch(Exception squish){}
}
return result;
}
#Override
protected void onPostExecute(String result){
myJSON=result;
showList();
}
}
GetDataJSON g = new GetDataJSON();
g.execute();
}
}
I have an update fragment using which i will update data in my database. Once the update is done i move back to 'view the data from database' fragment and i need the list to be updated. I think i have to write code for this inside onResume() but i don't know how to do it.
Code for 'view the data from database' fragment:
public class Testing extends Fragment {
String uname="921312104053";
private static final String TAG_RESULTS="result";
private static final String TAG_Sname = "Subject_name";
private static final String TAG_Scode = "Subject_code";
private static final String TAG_Sgrade ="Grade";
ListView lv;
JSONArray subjects = null;
String myJSON;
ListAdapter adapter;
ArrayList<HashMap<String, String>> subList,subList1;
public Testing() {
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_testing,
container, false);
disp(view);
return view;
}
public void disp(View view)
{
lv = (ListView)view.findViewById(R.id.list);
subList = new ArrayList<HashMap<String,String>>();
getData(view);
}
public void getData(View view){
class GetDataJSON extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... params) {
DefaultHttpClient httpclient = new DefaultHttpClient(new BasicHttpParams());
HttpPost httppost = new HttpPost("http://10.0.2.2/markolepsy/android_connect/testing.php?usrname="+uname);
httppost.setHeader("Content-type", "application/json");
InputStream inputStream = null;
String result = null;
try {
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
inputStream = entity.getContent();
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null)
{
sb.append(line + "\n");
}
result = sb.toString();
} catch (Exception e) {
}
finally {
try{if(inputStream != null)inputStream.close();}catch(Exception squish){}
}
return result;
}
#Override
protected void onPostExecute(String result){
myJSON=result;
showList();
}
}
GetDataJSON g = new GetDataJSON();
g.execute();
}
protected void showList(){
try {
JSONObject jsonObj = new JSONObject(myJSON);
subjects = jsonObj.getJSONArray(TAG_RESULTS);
for(int i=0;i<subjects.length();i++){
JSONObject c = subjects.getJSONObject(i);
String sname = c.getString(TAG_Sname);
String scode = c.getString(TAG_Scode);
String sgrade = c.getString(TAG_Sgrade);
HashMap<String,String> records = new HashMap<String,String>();
records.put(TAG_Sname,sname);
records.put(TAG_Scode,scode);
records.put(TAG_Sgrade,sgrade);
subList.add(records);
}
adapter = new SimpleAdapter(
getActivity(), subList, R.layout.list_layout,
new String[]{TAG_Sname,TAG_Scode,TAG_Sgrade},
new int[]{R.id.subject_name, R.id.subject_code, R.id.grade}
);
lv.setAdapter(adapter);
} catch (JSONException e) {
e.printStackTrace();
}
}
}
Using notifyDataSetChanged() may suite your needs.
Refer to this: How to refresh Android listview?
Edit:
adapter = new SimpleAdapter(
getActivity(), subList, R.layout.list_layout,
new String[]{TAG_Sname,TAG_Scode,TAG_Sgrade},
new int[]{R.id.subject_name, R.id.subject_code, R.id.grade}
);
lv.setAdapter(adapter);
adapter.notifyDataSetChanged();
The above code should help.
I am new in android.I am fetching data from mysql and showing it in listview.things are working fine but now i want to pass the value to intent when user click on listview(Row).I have implemented setOnItemClickListener.but the list view is dynamic so i am not getting how to get values and pass it to the intent.
Thanks in advance
public class AdminNotice extends Activity {
private String[] navMenuTitles;
private TypedArray navMenuIcons;
private EditText editTextName;
SharedPreferences sp;
private String jsonResult;
private ListView listView;
private Button b;
EditText etname, et;
TextView tv;
String myJSON;
private static final String TAG = "MainActivity.java";
private static final String TAG_NAME = "notice";
private static final String TAG_DATE = "ndate";
ProgressBar progressBar;
Date date;
JSONArray peoples = null;
ArrayList<HashMap<String, String>> personList;
ListView list;
public static final String USER_NAME = "USERNAME";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.noticelist);
progressBar = (ProgressBar) findViewById(R.id.progressbar);
//SharedPreferences myprefs= getSharedPreferences("user", MODE_WORLD_READABLE);
// String session_id= myprefs.getString("session_id", null);
//TextView textView = (TextView) findViewById(R.id.fname);
//textView.setText("Welcome "+session_id);
navMenuTitles = getResources().getStringArray(R.array.nav_drawer_items);
navMenuIcons = getResources().obtainTypedArray(R.array.nav_drawer_icons);
// load icons from
// strings.xml
list = (ListView) findViewById(R.id.listView);
personList = new ArrayList<HashMap<String,String>>();
getData();
}
//send messages stop
//get json data start
protected void showList(){
try {
JSONArray peoples = new JSONArray(myJSON);
for(int i=0;i<peoples.length();i++){
JSONObject c = peoples.getJSONObject(i);
String name=null, date=null;
/*if(c==null){
ProgressDialog progress = new ProgressDialog(this);
progress.setTitle("Loading");
progress.setMessage("Wait while loading...");
progress.show();
}*/
if(c.has("notice"))
if(c.has("ndate"))
progressBar.setVisibility(View.GONE);
name = c.getString("notice");
date = c.getString("ndate");
HashMap<String,String> persons = new HashMap<String,String>();
persons.put(TAG_NAME,name);
persons.put(TAG_DATE,date);
personList.add(persons);
}
ListAdapter adapter = new SimpleAdapter(
AdminNotice.this, personList, R.layout.list_item1,
new String[]{TAG_NAME,TAG_DATE},
new int[]{R.id.name, R.id.date}
);
list.setAdapter(adapter);
list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int position,
long id) {
/*ModelClass obj = getItem(position);
String name = obj.getName();*/
// Simple Toast to show the position Selected
Log.d("SELECT_POSITION", "Position For this List Item = " + position);
}
});
/* list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView parent, View view, int position, long id) {
Toast.makeText(getApplicationContext(), ((TextView) view).getText(), Toast.LENGTH_SHORT).show();
}
});*/
} catch (JSONException e) {
Log.i("tagconvertstr", "["+myJSON+"]");
}
}
public void getData(){
class GetDataJSON extends AsyncTask<String, Void, String>{
#Override
protected String doInBackground(String... params) {
SharedPreferences myprefs= getSharedPreferences("user", MODE_WORLD_READABLE);
String session_id= myprefs.getString("session_id", null);
InputStream inputStream = null;
String result = null;
try {
String postReceiverUrl = "http://notice.php";
// HttpClient
HttpClient httpClient = new DefaultHttpClient();
// post header
HttpPost httpPost = new HttpPost(postReceiverUrl);
// add your data
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
nameValuePairs.add(new BasicNameValuePair("username", session_id));
httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpClient.execute(httpPost);
HttpEntity resEntity = response.getEntity();
inputStream = resEntity.getContent();
// json is UTF-8 by default
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null)
{
sb.append(line + "\n");
}
result = sb.toString();
} catch (Exception e) {
Log.i("tagconvertstr", "["+result+"]");
System.out.println(e);
}
finally {
try{if(inputStream != null)inputStream.close();}catch(Exception squish){}
}
return result;
}
#Override
protected void onPostExecute(String result){
myJSON = result;
showList();
}
}
GetDataJSON g = new GetDataJSON();
g.execute();
}
//get json data stop
}
Inside your listview onItemClickListener
Intent intent=new Intent(currentyactivty.this,secondactiviy.class);
intent.putExtra("TAG_NAME", personList.get(position).get(TAG_NAME));
startActivity(intent);
To getdata in second activity at onCreate method
String data;
Intent in=getIntent();
if(in!=null && in.hasExtra("TAG_NAME")){
data=in.getStringArrayExtra("TAG_NAME");
}
you can set text from view
list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int position,
long id) {
Intent intent=new Intent(currentyactivty.this,secondactiviy.class);
intent.putExtra("NAME", personList.get(position).get(TAG_NAME));
startActivity(intent);
// Simple Toast to show the position Selected
Log.d("SELECT_POSITION", "Position For this List Item = " + position);
}
});
list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int position,
long id) {
/*ModelClass obj = getItem(position);
String name = obj.getName();*/
String personName = personList.get(position).get(TAG_NAME);
Intent i = new Intent(AdminNotice.this, YourNextActivity.class);
i.putExtra("person_name", personName);
startActivity(i);
// Simple Toast to show the position Selected
Log.d("SELECT_POSITION", "Position For this List Item = " + position);
}
});
you can use bundle to pass you're data from intent.
list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int position,
long id) {
ModelClass obj = getItem(position);
String name = obj.getName();
String date = obj.getDate();
Bundle bundle = new Bundle();
bundle.putString("name", name);
bundle.putString("date", date );
Intent in = new Intent(currentActivity.this,destinationActivity.class);
in.putExtras(b);
startActivity(in);
// Simple Toast to show the position Selected
Log.d("SELECT_POSITION", "Position For this List Item = " + position);
}
});
and you can get it in your other activity by doing.
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_second);
Intent in = getIntent();
Bundle b = in.getExtras();
String name = b.getString("name");
String date = b.getString("date);
}
with this approach you don't have to hit the database again to retrieve data and you're one query is saved.
similarly you can send just you're 'id' also if you want.
but if you just want to pass 'id' then #Nas method would be more sorted and easy.
I am new in android, i want to update my list view when ever data is inserted in mysql database.I have searched in internet and i have used adapter.notifyDataSetChanged(); but i keep getting the error "The method notifyDataSetChanged() is undefined for the type ListAdapter"
Code:
public class Messages extends BaseActivity{
private String[] navMenuTitles;
private TypedArray navMenuIcons;
private EditText editTextName;
SharedPreferences sp;
private String jsonResult;
private ListView listView;
private Button b;
EditText etname, et;
TextView tv;
String myJSON;
private static final String TAG = "MainActivity.java";
private static final String TAG_RESULTS="result";
private static final String TAG_USERNAME = "username";
private static final String TAG_NAME = "message_recd";
private static final String TAG_ADD ="message_sent";
JSONArray peoples = null;
ArrayList<HashMap<String, String>> personList;
ListView list;
public static final String USER_NAME = "USERNAME";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_first);
SharedPreferences myprefs= getSharedPreferences("user", MODE_WORLD_READABLE);
String session_id= myprefs.getString("session_id", null);
TextView textView = (TextView) findViewById(R.id.fname);
textView.setText("Welcome "+session_id);
navMenuTitles = getResources().getStringArray(R.array.nav_drawer_items);
navMenuIcons = getResources().obtainTypedArray(R.array.nav_drawer_icons);
// load icons from
// strings.xml
set(navMenuTitles, navMenuIcons);
editTextName = (EditText) findViewById(R.id.editTextName);
b=(Button)findViewById(R.id.button1);
list = (ListView) findViewById(R.id.listView);
personList = new ArrayList<HashMap<String,String>>();
getData();
b.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
etname=(EditText)findViewById(R.id.editTextName);
if( etname.getText().toString().trim().equals("")){
etname.setError( "Cannot be left empty!" );
}
// TODO Auto-generated method stub
else{
Intent intent = getIntent();
String fName = intent.getStringExtra("fname");
String message = etname.getText().toString();
insertToDatabase(message, fName);
}
etname.setText("");
}
});
}
//send messages start
private void insertToDatabase(String message, String fName1){
class SendPostReqAsyncTask extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... params) {
String paramUsername = params[0];
String fname = params[1];
//InputStream is = null;
String message = editTextName.getText().toString();
Intent intent1 = getIntent();
String fName = intent1.getStringExtra("fname");
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("message", message));
nameValuePairs.add(new BasicNameValuePair("username", fName));
try {
HttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost("http://10.0.2.2/test/test.php");
httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpClient.execute(httpPost);
HttpEntity entity = response.getEntity();
//is = entity.getContent();
} catch (ClientProtocolException e) {
} catch (IOException e) {
}
return "success";
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
Toast.makeText(getApplicationContext(), result, Toast.LENGTH_LONG).show();
}
}
SendPostReqAsyncTask sendPostReqAsyncTask = new SendPostReqAsyncTask();
sendPostReqAsyncTask.execute(message, fName1);
}
//send messages stop
//get json data start
protected void showList(){
try {
JSONArray peoples = new JSONArray(myJSON);
for(int i=0;i<peoples.length();i++){
JSONObject c = peoples.getJSONObject(i);
String name=null, address=null;
if(c.has("message_recd"))
name = c.getString("message_recd");
else
address = c.getString("message_sent");
HashMap<String,String> persons = new HashMap<String,String>();
persons.put(TAG_NAME,name);
persons.put(TAG_ADD,address);
personList.add(persons);
}
/*ListAdapter adapter = new SimpleAdapter(
Messages.this, personList, R.layout.list_item,
new String[]{TAG_NAME,TAG_ADD},
new int[]{R.id.name, R.id.address}
);*/
ListAdapter adapter = new SimpleAdapter(
Messages.this, personList, R.layout.list_item,
new String[]{TAG_NAME,TAG_ADD},
new int[]{R.id.name, R.id.address}
);
// http://www.vogella.com/tutorials/AndroidListView/article.html
// http://stackoverflow.com/questions/8166497/custom-adapter-for-list-view
list.setAdapter(adapter);
} catch (JSONException e) {
Log.i("tagconvertstr", "["+myJSON+"]");
}
}
public void getData(){
class GetDataJSON extends AsyncTask<String, Void, String>{
#Override
protected String doInBackground(String... params) {
SharedPreferences myprefs= getSharedPreferences("user", MODE_WORLD_READABLE);
String session_id= myprefs.getString("session_id", null);
InputStream inputStream = null;
String result = null;
try {
String postReceiverUrl = "http://10.0.2.2/progress_card/messages/get_messages.php";
// HttpClient
HttpClient httpClient = new DefaultHttpClient();
// post header
HttpPost httpPost = new HttpPost(postReceiverUrl);
// add your data
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
nameValuePairs.add(new BasicNameValuePair("username", session_id));
httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpClient.execute(httpPost);
HttpEntity resEntity = response.getEntity();
inputStream = resEntity.getContent();
// json is UTF-8 by default
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null)
{
sb.append(line + "\n");
}
result = sb.toString();
} catch (Exception e) {
Log.i("tagconvertstr", "["+result+"]");
System.out.println(e);
}
finally {
try{if(inputStream != null)inputStream.close();}catch(Exception squish){}
}
return result;
}
#Override
protected void onPostExecute(String result){
myJSON = result;
showList();
}
}
GetDataJSON g = new GetDataJSON();
g.execute();
}
//get json data stop
}
The notifyDataSetChanged method is defined and implemented in BaseAdapter, the supertype of SimpleAdapter. So just add a cast to BaseAdapter or SimpleAdapter.
when you perfrom any add() or remove() operation to your personlist,
call adpater.notifyDataSetChanged(); method to Update ListView
Refernce : notifyDataSetChanged example
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));