hello I am new to android in my app i have one ListFragment activity in which i am getting data perfectly where i have list of users now i want that after click on any user i need to show their profile
public class HomeFragment extends ListFragment {
//CustomAdapter adapter;
//private List<RowItem> rowItems;
private ProgressDialog pDialog;
//JSON parser class
JSONParser jsonParser = new JSONParser();
JSONArray matching=null;
ArrayList<HashMap<String,String>> aList;
private static String MATCH_URL = null;
private static final String TAG_MATCH="matching";
private static final String TAG_MATCH_ID="match_detail_id";
private static final String TAG_NAME="name";
private static final String TAG_PROFILE="profile_id";
private static final String TAG_IMAGE="image";
private static final String TAG_CAST="cast";
private static final String TAG_AGE="age";
private static final String TAG_LOCATION="location";
private ListView listview;
String user_match_id;
public HomeFragment(){}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
String strtext = getArguments().getString("user_login_id");
MATCH_URL = "http://abcd.com/webservice/matching?version=apps&user_login_id="+strtext;
View rootView = inflater.inflate(R.layout.fragment_home, container, false);
aList = new ArrayList<HashMap<String,String>>();
// rowItems = new ArrayList<RowItem>();
listview=(ListView)rootView.findViewById(android.R.id.list);
new LoadAlbums().execute();
return rootView;
}
class LoadAlbums extends AsyncTask<String, String, ArrayList<HashMap<String,String>>> {
/**
* Before starting background thread Show Progress Dialog
* */
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(getActivity());
pDialog.setMessage("Loading...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(false);
pDialog.show();
}
protected ArrayList<HashMap<String,String>> doInBackground(String... args) {
ServiceHandler sh = new ServiceHandler();
// Making a request to url and getting response
String jsonStr = sh.makeServiceCall(MATCH_URL, ServiceHandler.GET);
Log.d("Response: ", "> " + jsonStr);
ArrayList<HashMap<String,String>> listData = new ArrayList<HashMap<String, String>>();
if (jsonStr != null) {
try {
JSONObject jsonObj = new JSONObject(jsonStr);
// Getting JSON Array node
matching = jsonObj.getJSONArray(TAG_MATCH);
// looping through All Contacts
for (int i = 0; i < matching.length(); i++) {
JSONObject c = matching.getJSONObject(i);
// creating new HashMap
HashMap<String, String> map = new HashMap<String, String>();
// adding each child node to HashMap key => value
map.put(TAG_MATCH_ID, c.getString(TAG_MATCH_ID));
map.put(TAG_NAME,c.getString(TAG_NAME));
map.put(TAG_PROFILE, c.getString(TAG_PROFILE));
map.put(TAG_IMAGE, c.getString(TAG_IMAGE));
map.put(TAG_CAST, c.getString(TAG_CAST));
map.put(TAG_AGE, c.getString(TAG_AGE)+" years");
map.put(TAG_LOCATION, c.getString(TAG_LOCATION));
// adding HashList to ArrayList
listData.add(map);
}
} catch (JSONException e) {
e.printStackTrace();
}
} else {
Log.e("ServiceHandler", "Couldn't get any data from the url");
}
return listData;
}
protected void onPostExecute( ArrayList<HashMap<String,String>> result) {
super.onPostExecute(result);
// dismiss the dialog after getting all albums
if (pDialog.isShowing())
pDialog.dismiss();
// updating UI from Background Thread
/**
* Updating parsed JSON data into ListView
* */
listview.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
long arg3) {
// TODO Auto-generated method stub
Intent intent=new Intent(getActivity(),ProfileEdit.class);
intent.putExtra("match_detail_id", arg2);
startActivity(intent);
}
});
if(aList==null){
aList = new ArrayList<HashMap<String, String>>();
}
aList.addAll(result);
CustomAdapter adapter = new CustomAdapter(getActivity(),aList);
setListAdapter(adapter);
}
}
public class ProfilePage extends Activity{
private ProgressDialog pDialog;
AQuery androidAQuery=new AQuery(this);
//private static final String TAG_MATCH_ID="match_detail_id";
private static final String USER_NAME="name";
private static final String USER_AGE="age";
private static final String USER_LOCATION="location";
private static final String USER_MOTHER_TONGE="mother_tounge";
private static final String USER_OCCU="occupation";
private static final String USER_INCOM="income";
private static final String USER_HEIGHT="height";
private static final String USER_MARRAGE="marital_status";
private static final String USER_RELIGION="religion";
private static final String USER_GOTRA="gotra";
private static final String USER_MANGLIK="manglik";
private static final String USER_RASHI="rashi";
private static final String USER_EDUCATION="education";
private static final String USER_EAT="eating";
private static final String USER_DRINK="drink";
private static final String USER_SMOKE="smoke";
private static final String USER_ABOUT="about_me";
private static final String USER_PIC="profile_pic";
private static String USER_URL="";
String user_match_id;
private ImageView cover;
private ImageView yes;
private ImageView no;
private ImageView sendmsg;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.profile_page);
String matchId=this.getIntent().getStringExtra("match_detail_id");
if(matchId.trim().length()>0){
USER_URL="http://abcds.com/webservice/matchingdetails?version=apps&match_detail_id="+user_match_id;
}else{
Toast.makeText(ProfilePage.this,"match id blank",Toast.LENGTH_LONG).show();
}
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
ServiceHandler sh = new ServiceHandler();
// Making a request to url and getting response
String jsonStr = sh.makeServiceCall(USER_URL, ServiceHandler.GET);
Log.d("Response: ", "> " + jsonStr);
try {
JSONObject jsonObj = new JSONObject(jsonStr);
String user_name = jsonObj.getString(USER_NAME);
String user_age = jsonObj.getString(USER_AGE);
String user_location = jsonObj.getString(USER_LOCATION);
String user_mothertong = jsonObj.getString(USER_MOTHER_TONGE);
String user_occupation = jsonObj.getString(USER_OCCU);
String user_income = jsonObj.getString(USER_INCOM);
String user_height = jsonObj.getString(USER_HEIGHT);
String user_marg = jsonObj.getString(USER_MARRAGE);
String user_religion = jsonObj.getString(USER_RELIGION);
String user_gotra = jsonObj.getString(USER_GOTRA);
String user_manglik = jsonObj.getString(USER_MANGLIK);
String user_rashi = jsonObj.getString(USER_RASHI);
String user_education = jsonObj.getString(USER_EDUCATION);
String user_eat = jsonObj.getString(USER_EAT);
String user_drink = jsonObj.getString(USER_DRINK);
String user_smoke = jsonObj.getString(USER_SMOKE);
String user_about = jsonObj.getString(USER_ABOUT);
String user_pro = jsonObj.getString(USER_PIC);
final TextView uname = (TextView)findViewById(R.id.namedetail);
final TextView fdetail = (TextView)findViewById(R.id.firstdetail);
final TextView sdetail = (TextView)findViewById(R.id.seconddetail);
final TextView tdetail = (TextView)findViewById(R.id.thirddetail);
final TextView ocdetail=(TextView)findViewById(R.id.txtoccupationdetail);
final TextView incomedetail = (TextView)findViewById(R.id.incomedetaile);
final TextView uheight = (TextView)findViewById(R.id.txtheightprofile);
final TextView umrg = (TextView)findViewById(R.id.txtmrgprofile);
final TextView ureligion = (TextView)findViewById(R.id.prohindu);
final TextView ugotra = (TextView)findViewById(R.id.gothraa);
final TextView umanglik = (TextView)findViewById(R.id.usermanglik);
final TextView urashi = (TextView)findViewById(R.id.rashi);
final TextView udegree = (TextView)findViewById(R.id.userdegree);
final TextView ueat = (TextView)findViewById(R.id.txteatprofile);
final TextView udrink = (TextView)findViewById(R.id.txtdrinkprofile);
final TextView usmoke = (TextView)findViewById(R.id.txtsmokeprofile);
final TextView uabout = (TextView)findViewById(R.id.txtabouther);
final ImageView ucover = (ImageView)findViewById(R.id.coverimage);
uname.setText(user_name);
fdetail.setText(user_age+" years");
sdetail.setText(user_location);
tdetail.setText(user_mothertong);
ocdetail.setText(user_occupation);
incomedetail.setText(user_income);
uheight.setText(user_height);
umrg.setText(user_marg);
ureligion.setText(user_religion);
ugotra.setText(user_gotra);
umanglik.setText(user_manglik);
urashi.setText(user_rashi);
udegree.setText(user_education);
ueat.setText(user_eat);
udrink.setText(user_drink);
usmoke.setText(user_smoke);
uabout.setText(user_about);
androidAQuery.id(ucover).image(user_pro, true, true);
} catch (JSONException e) {
e.printStackTrace();
}
Try to override onListItemClick in fragment :
#Override
public void onListItemClick(ListView l, View v, int position, long id) {
Intent intent = new Intent(getActivity(), ProfilePage.class);
intent.putExtra("match_detail_id", aList.get(position).get(TAG_MATCH_ID));
startActivity(intent);
}
Instead of manual setOnItemClickListener to listview so no required this code :
listview=(ListView)rootView.findViewById(android.R.id.list);
listview.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,long arg3) {
Intent intent=new Intent(getActivity().getApplicationContext(),ProfileEdit.class);
intent.putExtra("position", arg2);
startActivity(intent);
}
});
Note : when you use ListFragment no need to find Listview and set item click as well as setAdapter manually,directly get all method ready like setAdapter() and onListItemClick.
Intent intent = new Intent(getBaseContext(), NewActivity.class);
intent.putExtra("KEY", Value);
startActivity(intent)
Try with below code:
listview.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
long arg3) {
// TODO Auto-generated method stub
Intent intent=new Intent(getActivity(),ProfileEdit.class);
intent.putExtra("match_detail_id", arg2);
startActivity(intent);
}
});
//get this data as below in ProfileEdit class
String matchId=this.getIntent().getStringExtra(""match_detail_id"");
if(matchId.trim().length()>0){
USER_URL="http://gujjumatch.com/webservice/matchingdetails?version=apps&match_detail_id="+user_match_id;
}else{
Toast.makeText(ProfileEdit.this,"match id blank",Toast.LENGTH_LONG).show();
}
Related
Could someone help me. I was following a very long tutorial and got to the end and can't fix this error. Starting at public void update list the code below is underlined in red and I can't seem to correct the problem.
public class readComments extends ListActivity {
private ProgressDialog pDialog;
private static final String READ_COMMENTS_URL = "http://120.120.1.100 /webservice/comments.php";
private static final String TAG_SUCCESS = "success";
private static final String TAG_TITLE = "title";
private static final String TAG_POSTS = "posts";
private static final String TAG_POST_ID = "post_id";
private static final String TAG_USERNAME = "username";
private static final String TAG_MESSAGE = "message";
private JSONArray mComments = null;
private ArrayList<HashMap<String, String>> mCommentList;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.read_comments);
}
#Override
protected void onResume() {
// TODO Auto-generated method stub
super.onResume();
//loading the comments via AsyncTask
new LoadComments().execute();
}
public void addComment(View v)
{
Intent i = new Intent(readComments.this, AddComment.class);
startActivity(i);
}
public void updateJSONdata() {
}
private void updateList() {
}
public class LoadComments extends AsyncTask<Void, Void, Boolean> {
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(readComments.this);
pDialog.setMessage("Loading Comments...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
public void updateJSONdata() {
mCommentList = new ArrayList<HashMap<String, String>>();
JSONParser jParser = new JSONParser();
JSONObject json = jParser.getJSONFromUrl(READ_COMMENTS_URL);
try {
mComments = json.getJSONArray(TAG_POSTS);
for (int i = 0; i < mComments.length(); i++) {
JSONObject c = mComments.getJSONObject(i);
String title = c.getString(TAG_TITLE);
String content = c.getString(TAG_MESSAGE);
String username = c.getString(TAG_USERNAME);
HashMap<String, String> map = new HashMap<String, String>();
map.put(TAG_TITLE, title);
map.put(TAG_MESSAGE, content);
map.put(TAG_USERNAME, username);
mCommentList.add(map);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
//Problem starts here everything underlined in red
#Override
private void updateList() {
ListAdapter adapter = new SimpleAdapter(this, mCommentList,
R.layout.single_post, new String[]{TAG_TITLE, TAG_MESSAGE,
TAG_USERNAME}, new int[]{R.id.title, R.id.message,
R.id.username});
setListAdapter(adapter);
ListView lv = getListView();
lv.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
}
});
}
I'm a beginner, I'm creating a job search app which shows job infomation as listview where the data is from WAMP server database. I encounter a problem : Cannot resolve method 'getStringArrayList' , when I'm making a search filter for this Listview. Please see line 11 of SearchFilter.java. Could anyone help? thank you very much!
SearchFilter.java
public class SearchFilter extends ListActivity {
private EditText filterText = null;
ArrayAdapter<String> adapter = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
filterText = (EditText) findViewById(R.id.search_box);
filterText.addTextChangedListener(filterTextWatcher);
setListAdapter(new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1,
getStringArrayList())); ***<<<<< this line !***
}
private TextWatcher filterTextWatcher = new TextWatcher() {
public void afterTextChanged(Editable s) {
}
public void beforeTextChanged(CharSequence s, int start, int count,
int after) {
}
public void onTextChanged(CharSequence s, int start, int before,
int count) {
adapter.getFilter().filter(s);
}
};
#Override
protected void onDestroy() {
super.onDestroy();
filterText.removeTextChangedListener(filterTextWatcher);
}
}
MainActivity.java
public class MainActivity extends ListActivity {
private ProgressDialog pDialog;
// URL to get contacts JSON
private static String url = "http://192.168.0.102/get_json_select_all.php";
// JSON Node names
private static final String TAG_INFO = "info";
private static final String TAG_POSTNAME = "PostName";
private static final String TAG_LOCATION = "Location";
private static final String TAG_SALARY = "Salary";
private static final String TAG_RESPONSIBILITY = "Responsibility";
private static final String TAG_COMPANY = "Company";
private static final String TAG_CONTACT = "Contact";
// contacts JSONArray
JSONArray infos = null;
// Hashmap for ListView
ArrayList<HashMap<String, String>> infoList;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
infoList = new ArrayList<HashMap<String, String>>();
final 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 name = ((TextView) view.findViewById(R.id.PostName))
.getText().toString();
String cost = ((TextView) view.findViewById(R.id.Location))
.getText().toString();
String description = ((TextView) view.findViewById(R.id.Salary))
.getText().toString();
HashMap<String, String> info = new HashMap<String, String>();
info=(HashMap<String, String>)lv.getAdapter().getItem(position);
// Starting single contact activity
Intent in = new Intent(getApplicationContext(),
SingleContactActivity.class);
in.putExtra(TAG_POSTNAME, name);
in.putExtra(TAG_LOCATION, cost);
in.putExtra(TAG_SALARY, description);
in.putExtra(TAG_RESPONSIBILITY, info.get(TAG_RESPONSIBILITY));
in.putExtra(TAG_COMPANY, info.get(TAG_COMPANY));
in.putExtra(TAG_CONTACT, info.get(TAG_CONTACT));
startActivity(in);
}
});
// 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(MainActivity.this);
pDialog.setMessage("Please wait...");
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);
// Getting JSON Array node
infos = jsonObj.getJSONArray(TAG_INFO);
// looping through All Contacts
for (int i = 0; i < infos.length(); i++) {
JSONObject c = infos.getJSONObject(i);
String id = c.getString(TAG_POSTNAME);
String name = c.getString(TAG_LOCATION);
String email = c.getString(TAG_SALARY);
String address = c.getString(TAG_RESPONSIBILITY);
String gender = c.getString(TAG_COMPANY);
// Phone node is JSON Object
String mobile = c.getString(TAG_CONTACT);
// tmp hashmap for single contact
HashMap<String, String> info = new HashMap<String, String>();
// adding each child node to HashMap key => value
info.put(TAG_POSTNAME, id);
info.put(TAG_LOCATION, name);
info.put(TAG_SALARY, email);
info.put(TAG_RESPONSIBILITY, address);
info.put(TAG_COMPANY, gender);
info.put(TAG_CONTACT, mobile);
// adding contact to contact list
infoList.add(info);
}
} catch (JSONException e) {
e.printStackTrace();
}
} else {
Log.e("ServiceHandler", "Couldn't get any data from the url");
}
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, infoList,
R.layout.list_item, new String[] { TAG_POSTNAME, TAG_LOCATION,
TAG_SALARY }, new int[] { R.id.PostName,
R.id.Location, R.id.Salary });
setListAdapter(adapter);
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_main, menu);
return (super.onCreateOptionsMenu(menu));
}
}
activity_main.xml
<EditText android:id="#+id/search_box"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:hint="Search Jobs"
android:inputType="text"
android:maxLines="1"/>
<ListView
android:id="#android:id/list"
android:layout_width="fill_parent"
android:layout_height="wrap_content"/>
getStringArrayList is a method on Bundle (such as savedInstanceState). There's no such method in Activity. Hope that helps.
Currently your infoList is an ArrayList>, something that is harder to pass directly to an activity. So find a way to represent it as an ArrayList, or find a more suitable datatype supported by Intent's putExtra-methods. Here below is a suggested solution using an ArrayList.
Passing the data into the activity with the Intent allows you to get it back in your SearchFilter. In the calling activity put something like this:
Intent i = new Intent(this, SearchFilter.class);
i.putStringArrayListExtra("com.yourpackagename.here.keynamehere", aStringArrayList);
In SearchFilter.java, put something like this:
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
filterText = (EditText) findViewById(R.id.search_box);
filterText.addTextChangedListener(filterTextWatcher);
Intent startingIntent = getIntent();
ArrayList<String> arrayList = new ArrayList<String>();
if (startingIntent != null) {
arrayList = startingIntent.getStringArrayList("com.yourpackagename.here.keynamehere");
}
setListAdapter(new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1,
arrayList));
}
I can insert data into database but now face the problem that cannot retrieve data from the database and display in listview in android. Here is my coding part for retrieve data. Hope someone can help to solve this, thank you.
package com.example.iuum;
private ProgressDialog pDialog;
private static final String READ_COMMENTS_URL = "http://10.19.229.212/webservice/comments.php";
private static final String TAG_SUCCESS = "success";
private static final String TAG_TITLE = "title";
private static final String TAG_POSTS = "posts";
private static final String TAG_POST_ID = "post_id";
private static final String TAG_USERNAME = "username";
private static final String TAG_MESSAGE = "message";
private JSONArray mComments = null;
private ArrayList<HashMap<String, String>> mCommentList;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_forum1a);
}
#Override
protected void onResume() {
super.onResume();
new LoadComments().execute();
}
public void clickbtnWrite(View v) {
Intent i = new Intent(Forum1a.this, AddForum.class);
startActivity(i);
}
/**
* Retrieves recent post data from the server.
*/
public void updateJSONdata() {
mCommentList = new ArrayList<HashMap<String, String>>();
JSONParser jParser = new JSONParser();
JSONObject json = jParser.getJSONFromUrl(READ_COMMENTS_URL);
try {
mComments = json.getJSONArray(TAG_POSTS);
for (int i = 0; i < mComments.length(); i++) {
JSONObject c = mComments.getJSONObject(i);
// gets the content of each tag
String title = c.getString(TAG_TITLE);
String content = c.getString(TAG_MESSAGE);
String username = c.getString(TAG_USERNAME);
HashMap<String, String> map = new HashMap<String, String>();
map.put(TAG_TITLE, title);
map.put(TAG_MESSAGE, content);
map.put(TAG_USERNAME, username);
mCommentList.add(map);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
/**
* Inserts the parsed data into the listview.
*/
private void updateList() {
ListAdapter adapter = new SimpleAdapter(this, mCommentList,
R.layout.singelpost, new String[] { TAG_TITLE, TAG_MESSAGE,
TAG_USERNAME }, new int[] { R.id.title, R.id.message,
R.id.username });
setListAdapter(adapter);
ListView lv = getListView();
lv.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
}
});
}
public class LoadComments extends AsyncTask<Void, Void, Boolean> {
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(Forum1a.this);
pDialog.setMessage("Loading Comments...");
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();
}
}
}
Add ListView in activity_forum1a.xml
<ListView
android:id="#+id/list_view"
android:layout_width="match_parent"
android:layout_height="wrap_content"></ListView>
Take ListView reference
private ListView mList;
Initialize it in onCreate
mList = (ListView) findViewById(R.id.list_view);
Take ListAdapter class Refernce
private ListAdapter listAdapter;
Add setListAdapter method
public void setListAdapter(ListAdapter listAdapter) {
this.listAdapter = listAdapter;
mList.setAdapter(listAdapter);
}
Change updateList method to
/**
* Inserts the parsed data into the listview.
*/
private void updateList() {
ListAdapter adapter = new SimpleAdapter(this, mCommentList,
R.layout.test, new String[] { TAG_TITLE, TAG_MESSAGE,
TAG_USERNAME }, new int[] { R.id.title, R.id.message,
R.id.username });
setListAdapter(adapter);
}
and perform item click operation outside from the method, by implementing onItemClickListener
i want make some process in my aplication to input some text first, after that, When user clicks the done button on the screen keyboard(using android:imeOptions="actionSearch") Isome data will show from this url :
("http://www.aaaa.com/selectAgent.htm?n="+cari_agen);
but when i make some process, there's nothing happen, my code still load all data, not specific as cari_agen, this is my source code :
public class MainActivity extends Activity {
GridView gridView;
private static final String ATASAN = "atasan";
private static final String KODE_AGEN = "kode_agen";
private static final String JENIS = "jenis";
private static final String NO_AAJI = "no_aaji";
private static final String NAMA_AGEN = "nama_agen";
List AgenList = new ArrayList();
boolean boolStatusKoneksi=true;
private ProgressDialog Dialog;
protected Context applicationContext;
EditText cari;
SearchView search;
#Override
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.mainmenu);
search=(SearchView) findViewById(R.id.searchView1);
cari=(EditText) findViewById(R.id.search);
cari.setOnEditorActionListener(new OnEditorActionListener() {
#Override
public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
if (actionId == EditorInfo.IME_ACTION_SEARCH) {
new AgenAsyncTask().execute();
return true;
}
return false;
}
});
}
public class AgenAsyncTask extends AsyncTask<String, String, String>
{
String cari_agen = cari.getText().toString();
#Override
protected void onPreExecute() {
super.onPreExecute();
Dialog = new ProgressDialog(MainActivity.this);
Dialog.setMessage("Mohon Tunggu sebentar...");
Dialog.setIndeterminate(false);
Dialog.setCancelable(true);
Dialog.show();
}
protected String doInBackground(String... args) {
String url =("http://www.aaaa.com/selectAgent.htm?n="+cari_agen);
try{
JSONParser j=new JSONParser();
JSONArray jsonArray = j.takeJson(url);
for(int i =0; i<jsonArray.length(); i++)
{
JSONObject c = jsonArray.getJSONObject(i);
HashMap<String, String> map = new HashMap<String, String>();
if (c.has("nama_agen"))
Log.v(NAMA_AGEN,"Nama agen=") ;
map.put("nama_agen", c.get("nama_agen").toString());
if (c.has("atasan"))
map.put("atasan", c.get("atasan").toString());
if (c.has("jenis"))
map.put("jenis", c.get("jenis").toString());
AgenList.add(map);
if (c.has("no_aaji"))
map.put("no_aaji", c.get("no_aaji").toString());
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(String arg)
{
Dialog.dismiss();
GridView gridview = (GridView) findViewById(R.id.gridview);
ListAdapter adapter = new SimpleAdapter(
MainActivity.this, AgenList, R.layout.list_item,
new String[] { NAMA_AGEN, ATASAN, JENIS,NO_AAJI }, new int [] {R.id.nama_agen, R.id.atasan, R.id.jenis,R.id.no_aaji});
gridview.setAdapter(adapter); }
i hope somebody can help me to solve this problem, thank u
Currently i'm working on How to find the items from the listview when given the keyword for the item in edittext, the listview becomes empty and the output is displaying in toast message, can anybody help like how to make the found "item" to display it in listivew?
public class Home extends ListActivity {
//how many to load on reaching the bottom
int itemsPerPage = 15;
boolean loadingMore = false;
ArrayList<String> songsList;
ListView list;
LazyAdapter adapter, adapter1;
JSONArray posts;
//ArrayList thats going to hold the search results
ArrayList<HashMap<String, String>> searchResults;
LayoutInflater inflater;
// All static variables
static final String URL = "http://abc.net/ads/?json=get_recent_posts";
static final String KEY_POSTS = "posts";
static final String KEY_ID = "id";
static final String KEY_TITLE = "title";
static final String KEY_DATE = "date";
static final String KEY_CONTENT = "content";
static final String KEY_AUTHOR = "author";
static final String KEY_NAME = "name";
static final String KEY_ATTACHMENTS = "attachments";
static final String KEY_SLUG = "slug";
static final String KEY_THUMB_URL = "thumbnail";
static final String KEY_IMAGES = "images";
static final String KEY_URL = "url";
private static final String DEBUGTAG = null;
protected static final String TAG = null;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
final EditText searchBox=(EditText) findViewById(R.id.search);
final ListView list=(ListView)findViewById(android.R.id.list);
//get the LayoutInflater for inflating the customomView
//this will be used in the custom adapter
inflater=(LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
final ArrayList<HashMap<String, String>> songsList = new ArrayList<HashMap<String, String>>();
// Creating JSON Parser instance
final JSONParser jParser = new JSONParser();
// getting JSON string from URL
JSONObject json = jParser.getJSONFromUrl(URL);
try {
posts = json.getJSONArray(KEY_POSTS);
// looping through all song nodes <song>
for(int i = 0; i < posts.length(); i++){
JSONObject c = posts.getJSONObject(i);
// Storing each json item in variable
String id = c.getString(KEY_ID);
String title = c.getString(KEY_TITLE);
String date = c.getString(KEY_DATE);
String content = c.getString(KEY_CONTENT);
// to remove all <P> </p> and <br /> and replace with ""
content = content.replace("<br />", "");
content = content.replace("<p>", "");
content = content.replace("</p>", "");
//authornumber is agin JSON Object
JSONObject author = c.getJSONObject(KEY_AUTHOR);
String name = author.getString(KEY_NAME);
String url = null;
String slug = null;
try {
JSONArray atta = c.getJSONArray("attachments");
for(int j = 0; j < atta.length(); j++){
JSONObject d = atta.getJSONObject(j);
slug = d.getString(KEY_SLUG);
JSONObject images = d.getJSONObject(KEY_IMAGES);
JSONObject thumbnail = images.getJSONObject(KEY_THUMB_URL);
url = thumbnail.getString(KEY_URL);
}
} catch (Exception e) {
e.printStackTrace();
}
// creating new HashMap
HashMap<String, String> map = new HashMap<String, String>();
// adding each child node to HashMap key => value
map.put(KEY_ID, id);
map.put(KEY_TITLE, title);
map.put(KEY_DATE, date);
map.put(KEY_NAME, name);
map.put(KEY_CONTENT, content);
map.put(KEY_SLUG, slug);
map.put(KEY_URL, url);
// adding HashList to ArrayList
songsList.add(map);
}
}catch (JSONException e) {
e.printStackTrace();
}
//searchResults=OriginalValues initially
searchResults=new ArrayList<HashMap<String, String>>(songsList);
// Getting adapter by passing json data ArrayList
adapter = new LazyAdapter(this, songsList);
list.setAdapter(adapter);
searchBox.addTextChangedListener(new TextWatcher() {
public void onTextChanged(CharSequence s, int start, int before, int count) {
//get the text in the EditText
String searchString = searchBox.getText().toString();
int textLength = searchString.length();
//clear the initial data set
searchResults.clear();
for (int i = 0; i < songsList.size(); i++) {
String playerName = songsList.get(i).get("title").toString();
if (textLength <= playerName.length()) {
//compare the String in EditText with Names in the ArrayList
if (searchString.equalsIgnoreCase(playerName.substring(0, textLength)))
Toast.makeText(getApplicationContext(), playerName, 1).show();
Home.this.adapter.getFilter();
searchResults.add(songsList.get(i));
Log.d(TAG, "title");
}
}
adapter.notifyDataSetChanged();
list.setAdapter(new ArrayAdapter<String>
(Home.this,
R.layout.activity_home));
}
public void beforeTextChanged(CharSequence s, int start, int count,
int after) {
}
public void afterTextChanged(Editable s) {
Home.this.adapter.getFilter();
}
});
adapter.notifyDataSetChanged();
list.setAdapter(new ArrayAdapter<String>(Home.this, R.layout.activity_home));
You are not giving any data set to populate the ListView.
Just like you initially populated the ListView with songsList data
adapter = new LazyAdapter(this, songsList);
list.setAdapter(adapter);
use:
adapter = new LazyAdapter(this, searchResults);
list.setAdapter(adapter);
try this,
edittext code for search
etSearch.addTextChangedListener(new TextWatcher() {
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
// Call back the Adapter with current character to Filter
adapter1.getFilter().filter(s.toString());
}
........
add arraylist to listview to display
adapter1 = new MyAdapter(MainActivity.this, mProductArrayList);
lvProducts.setAdapter(adapter1);
Adapter Class
public class MyAdapter extends BaseAdapter implements Filterable {
private ArrayList<Product> mOriginalValues; // Original Values
private ArrayList<Product> mDisplayedValues; // Values to be displayed
LayoutInflater inflater;
public MyAdapter(Context context, ArrayList<Product> mProductArrayList) {
this.mOriginalValues = mProductArrayList;
this.mDisplayedValues = mProductArrayList;
inflater = LayoutInflater.from(context);
}
..........
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
ViewHolder holder = null;
if (convertView == null) {
holder = new ViewHolder();
convertView = inflater.inflate(R.layout.row, null);
holder.llContainer = (LinearLayout)convertView.findViewById(R.id.llContainer1);
holder.tvName = (TextView) convertView.findViewById(R.id.tvName);
holder.tvPrice = (TextView) convertView.findViewById(R.id.tvPrice);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
holder.tvName.setText(mDisplayedValues.get(position).name);
holder.tvPrice.setText(mDisplayedValues.get(position).price+"");
holder.llContainer.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
Toast.makeText(MainActivity.this, mDisplayedValues.get(position).price.toString() , Toast.LENGTH_SHORT).show();
}
});
return convertView;
}