Pass data from a listview to a new activity - android

Can someone help me with following issue:
When I click on an item in the listview, I need to open a new activity with the data from the listview...
here is my code:
public class listar_clientes extends ListActivity {
private ProgressDialog pDialog;
// Creating JSON Parser object
JSONParser jParser = new JSONParser();
ArrayList<HashMap<String, String>> productsList;
// url to get all products list
private static String url_all_products = "http://192.168.137.100:81/androidapp/listar_clientes.php";
// JSON Node names
private static final String TAG_CLIENTE= "clientes";
private static final String TAG_NOME = "nome";
private static final String TAG_ABV = "nome2";
// products JSONArray
JSONArray products = null;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_listar_clientes);
// Hashmap for ListView
productsList = new ArrayList<HashMap<String, String>>();
// Loading products in Background Thread
new LoadAllProducts().execute();
// Log.v("COUNT-->",productsList.get(0).toString());
// Get listview
ListView list = getListView();
// launching Edit Product Screen
// lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
//
//
// // Starting new intent
// Intent in = new Intent(getApplicationContext(),
// list_item.class);
// // sending pid to next activity
// in.putExtra(TAG_PID, pid);
//
// // starting new activity and expecting some response back
// startActivityForResult(in, 100);
// }
// });
/* ListAdapter adapter = new SimpleAdapter(
encomendas_user.this, productsList,
R.layout.activity_list_item, new String[] { TAG_IDUSER,
TAG_TITULO},
new int[] { R.id.pid, R.id.name });
// updating listview
setListAdapter(adapter);*/
// on seleting single product
// launching Edit Product Screen
}
// Response from Edit Product Activity
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
// if result code 100
if (resultCode == 100) {
// if result code 100 is received
// means user edited/deleted product
// reload this screen again
Intent intent = getIntent();
finish();
startActivity(intent);
}
}
/**
* Background Async Task to Load all product by making HTTP Request
* */
class LoadAllProducts extends AsyncTask<String, String, String> {
/**
* Before starting background thread Show Progress Dialog
* */
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(listar_clientes.this);
pDialog.setMessage("A Carregar dados. Por favor Aguarde...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(false);
pDialog.show();
}
/**
* getting All products from url
* */
protected String doInBackground(String... args) {
// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
// getting JSON string from URL
JSONObject json = jParser.makeHttpRequest(url_all_products, "GET", params);
// Check your log cat for JSON reponse
Log.d("All Products: ", json.toString());
try {
// Checking for SUCCESS TAG
// int success = json.getInt(TAG_IDUSER);
//Log.d("NAMSUCCESSE: ", ""+success);
//if (success == 1) {
// products found
// Getting Array of Products
products = json.getJSONArray(TAG_CLIENTE);
// looping through All Products
for (int i = 0; i < products.length(); i++) {
JSONObject c = products.getJSONObject(i);
// Storing each json item in variable
String name = c.getString(TAG_NOME);
String abv = c.getString(TAG_ABV);
Log.d("NAME TESTE: ", name);
// creating new HashMap
HashMap<String, String> map = new HashMap<String, String>();
// adding each child node to HashMap key => value
map.put(TAG_NOME, "Nome:"+" "+ name);
map.put(TAG_ABV, "Abreviatura:"+" "+abv);
// if(UserInfo.userID==(Integer.parseInt(name))){
// adding HashList to ArrayList
productsList.add(map);
// }
}
/* } else {
// no products found
// Launch Add New product Activity
//Intent i = new Intent(getApplicationContext(),
// NewProductActivity.class);
// Closing all previous activities
//i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
// startActivity(i);
}*/
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
/**
* After completing background task Dismiss the progress dialog
* **/
protected void onPostExecute(String file_url) {
// dismiss the dialog after getting all products
pDialog.dismiss();
// updating UI from Background Thread
runOnUiThread(new Runnable() {
public void run() {
/**
* Updating parsed JSON data into ListView
* */
ListAdapter adapter = new SimpleAdapter(
listar_clientes.this, productsList,
R.layout.activity_list_item_clientes, new String[] { TAG_NOME, TAG_ABV},
new int[] { R.id.name, R.id.abv});
// updating listview
setListAdapter(adapter);
}
});
}
/*private AdapterView.OnItemClickListener OnListClick=new AdapterView.OnItemClickListener(){
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Intent i = new Intent(listar_clientes.this, detalhes_cliente.class);
in.putExtra(TAG_NOME, id_user.getText().toString());
startActivity(i);
}
}*/
public void detalhes (View v){
Intent i = new Intent(listar_clientes.this, detalhes_cliente.class);
}
}
}
here is the xml code:
<?xml version="1.0" encoding="utf-8"?>
<ScrollView
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/scroll"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:fillViewport="false">
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:paddingBottom="5dp"
android:longClickable="true"
android:padding="10dp"
android:onClick="detalhes"
>
<!-- Product id (pid) - will be HIDDEN - used to pass to other activity -->
<TextView
android:id="#+id/pid"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:visibility="gone"
android:paddingBottom="5dp"/>
<!-- Name Label -->
<TextView
android:id="#+id/name"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:paddingTop="6dip"
android:paddingLeft="6dip"
android:textSize="17dip"
android:textStyle="bold"
android:textColor="#ff014cff"
android:text="Nome Cliente"
android:paddingBottom="5dp"/>
<TextView
android:id="#+id/abv"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_below="#+id/name"
android:paddingTop="6dip"
android:paddingLeft="6dip"
android:textSize="17dip"
android:textStyle="bold"
android:textColor="#ff000000"
android:text="Abreviatura" />
</RelativeLayout>
</ScrollView>

Just Change your method as per your data to be send.
public void detalhes (View v){
Intent i = new Intent(listar_clientes.this, detalhes_cliente.class);
Bundle mBundle = new Bundle();
mBundle.putString(key1, value1);
mBundle.putInt(key2,value2);
mBundle.putStringArray(key3, value3);
mBundle.putStringArrayList(key4, value4);
..
....
mBundle.putInt(key, value);
i.putExtras(mBundle);
startActivity(i);
}
for reference you can use this link for how you get back your data from the bundle and more clarity.
may this will helpful ..Thanks

Pass data from onItemClick of ListView to other Activity
Initialize variable:
private ListView listView;
Bind View:
listView = (ListView)findViewById(R.id.listView);
onItemClick Of ListView:
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Intent intent = new Intent(this, Your_New_Activity.class);
intent.putExtra("key 1", "Value 1");
intent.putExtra("key 2", "Value 2");
intent.putExtra("key 3", "Value 3");
startActivity(intent);
}
});
Now Receive data on onCreate of New Activity:
String key_one = getIntent().getStringExtra("key 1");
String key_two = getIntent().getStringExtra("key 2");
String key_three = getIntent().getStringExtra("key 3");
Done

Related

i want to fetch items at particular interval of time in android

public class AllProductsActivity extends ListActivity {
// Progress Dialog
private ProgressDialog pDialog;
// Creating JSON Parser object
JSONParser jParser = new JSONParser();
ArrayList<HashMap<String, String>> productsList;
// url to get all products list
private static String url_all_products = "http://www.rush.com/android_connect/get_all_products.php";
// JSON Node names
private static final String TAG_SUCCESS = "success";
private static final String TAG_PRODUCTS = "products";
private static final String TAG_PID = "pid";
private static final String TAG_NAME = "name";
// products JSONArray
JSONArray products = null;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.all_products);
// Hashmap for ListView
productsList = new ArrayList<HashMap<String, String>>();
// Loading products in Background Thread
new LoadAllProducts().execute();
// Get listview
ListView lv = getListView();
// on seleting single product
// launching Edit Product Screen
lv.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// getting values from selected ListItem
String pid = ((TextView) view.findViewById(R.id.pid)).getText()
.toString();
// Starting new intent
Intent in = new Intent(getApplicationContext(),
EditProductActivity.class);
// sending pid to next activity
in.putExtra(TAG_PID, pid);
// starting new activity and expecting some response back
startActivityForResult(in, 100);
}
});
}
// Response from Edit Product Activity
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
// if result code 100
if (resultCode == 100) {
// if result code 100 is received
// means user edited/deleted product
// reload this screen again
Intent intent = getIntent();
finish();
startActivity(intent);
}
}
/**
* Background Async Task to Load all product by making HTTP Request
* */
class LoadAllProducts extends AsyncTask<String, String, String> {
/**
* Before starting background thread Show Progress Dialog
* */
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(AllProductsActivity.this);
pDialog.setMessage("Loading products. Please wait...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(false);
pDialog.show();
}
/**
* getting All products from url
* */
protected String doInBackground(String... args) {
// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
// getting JSON string from URL
JSONObject json = jParser.makeHttpRequest(url_all_products, "GET", params);
// Check your log cat for JSON reponse
Log.d("All Products: ", json.toString());
try {
// Checking for SUCCESS TAG
int success = json.getInt(TAG_SUCCESS);
if (success == 1) {
// products found
// Getting Array of Products
products = json.getJSONArray(TAG_PRODUCTS);
// looping through All Products
for (int i = 0; i < products.length(); i++) {
JSONObject c = products.getJSONObject(i);
// Storing each json item in variable
String id = c.getString(TAG_PID);
String name = c.getString(TAG_NAME);
// creating new HashMap
HashMap<String, String> map = new HashMap<String, String>();
// adding each child node to HashMap key => value
map.put(TAG_PID, id);
map.put(TAG_NAME, name);
// adding HashList to ArrayList
productsList.add(map);
}
} else {
// no products found
// Launch Add New product Activity
Intent i = new Intent(getApplicationContext(),
NewProductActivity.class);
// Closing all previous activities
i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(i);
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
/**
* After completing background task Dismiss the progress dialog
* **/
protected void onPostExecute(String file_url) {
// dismiss the dialog after getting all products
pDialog.dismiss();
// updating UI from Background Thread
runOnUiThread(new Runnable() {
public void run() {
/**
* Updating parsed JSON data into ListView
* */
ListAdapter adapter = new SimpleAdapter(
AllProductsActivity.this, productsList,
R.layout.list_item, new String[] { TAG_PID,
TAG_NAME},
new int[] { R.id.pid, R.id.name });
// updating listview
setListAdapter(adapter);
}
});
}
}
}
This is my code to view all product and it gives complete output . But each and every time i have to refresh manually to show new items...
Now i want to do auto refresh at every 10 seconds for retrieve all the product list....
so how can i do that?
You can user TimerTask. see TimerTask
see example
if(timer != null){
timer.cancel();
}
//re-schedule timer here
//otherwise, IllegalStateException of
//"TimerTask is scheduled already"
//will be thrown
timer = new Timer();
myTimerTask = new MyTimerTask();
if(optSingleShot.isChecked()){
//singleshot delay 1000 ms
timer.schedule(myTimerTask, 1000);
}else{
//delay 1000ms, repeat in 5000ms
timer.schedule(myTimerTask, 1000, 5000);
}
Timer Class
class MyTimerTask extends TimerTask {
#Override
public void run() {
new LoadAllProducts().execute();
}
}
}
example refer this
// Loading products in Background Thread
new LoadAllProducts().execute();
use below one instead of abve one
new LoadAllProducts().execute(); //first time load
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
setListAdapter(null);
new LoadAllProducts().execute();
}
}, 10000);//you specify the particular time
You can try what given below -
Timer t;
t = new Timer();
t.scheduleAtFixedRate(new TimerTask() {
private Context context;
#Override
public void run() {
// do your task that you want to refresh at reguler interval
}
},
//Set how long before to start calling the TimerTask (in milliseconds)
startdelay,
//Set the amount of time between each execution (in milliseconds)
timeinterval
);

Calling specific activities in android when listview item is clicked

I want to call a specific Activity when a list item is clicked. Using if statements or case in my ListView click event handler and using String fclass_state variable, I have 4 activities to be called. How do I go about it?
public class OutletsList extends ListActivity{
// Progress Dialog
private ProgressDialog pDialog;
// testing on Emulator:
private static final String READ_COMMENTS_URL = "myurl";
// JSON IDS:
private static final String TAG_SUCCESS = "success";
private static final String TAG_OUTLET_NAME = "outlet_name";
private static final String TAG_POSTS = "posts";
private static final String TAG_SPARKLING_CLASSIFICATION = "sparkling_classification";
private static final String TAG_SPARKLING_CHANNEL = "sparkling_channel";
private static final String TAG_CLASS = "class";
// An array of all of our comments
private JSONArray mOutlets = null;
// manages all of our comments in a list.
private ArrayList<HashMap<String, String>> mOutletsList;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.outlets_list);
}
#Override
protected void onResume() {
// TODO Auto-generated method stub
super.onResume();
// loading the comments via AsyncTask
new LoadMathQuestions().execute();
}
/* public void addComment(View v) {
Intent i = new Intent(ReadComments.this, AddComment.class);
startActivity(i);
}
*/
/**
* Retrieves recent post data from the server.
*/
public void updateJSONdata() {
// Instantiate the arraylist to contain all the JSON data.
// we are going to use a bunch of key-value pairs, referring
// to the json element name, and the content.
mOutletsList = new ArrayList<HashMap<String, String>>();
// Instantiating the json parser J parser
JSONParser jParser = new JSONParser();
// Feed the beast our comments url, and it spits us
// back a JSON object. Boo-yeah Jerome.
JSONObject json = jParser.getJSONFromUrl(READ_COMMENTS_URL);
//Catcing Exceptions
try {
//Checking the amount of data rows.
mOutlets = json.getJSONArray(TAG_POSTS);
// looping through the database
for (int i = 0; i < mOutlets.length(); i++) {
JSONObject c = mOutlets.getJSONObject(i);
// gets the content of each tag
String outlet = c.getString(TAG_OUTLET_NAME);
String schannel = c.getString(TAG_SPARKLING_CHANNEL);
String spclassification = c.getString(TAG_SPARKLING_CLASSIFICATION);
String cls = c.getString(TAG_CLASS);
HashMap<String, String> map = new HashMap<String, String>();
map.put(TAG_OUTLET_NAME, outlet );
map.put(TAG_SPARKLING_CHANNEL, schannel);
map.put(TAG_SPARKLING_CLASSIFICATION, spclassification);
map.put(TAG_CLASS, cls);
// adding HashList to ArrayList
mOutletsList.add(map);
// JSON data parsing completed by hash mappings
// list
}
} catch (JSONException e) {
e.printStackTrace();
}
}
/**
* Inserts the parsed data into the listview.
*/
private void updateList() {
// For a ListActivity we need to set the List Adapter, and in order to do
//that, we need to create a ListAdapter. This SimpleAdapter,
//will utilize our updated Hashmapped ArrayList,
//use our single_post xml template for each item in our list,
//and place the appropriate info from the list to the
//correct GUI id. Order is important here.
ListAdapter adapter = new SimpleAdapter(this, mOutletsList,
R.layout.single_outlet, new String[] { TAG_OUTLET_NAME, TAG_SPARKLING_CHANNEL,
TAG_SPARKLING_CLASSIFICATION, TAG_CLASS}, new int[]
{ R.id.outlet_name, R.id.sparkling_channel, R.id.sparkling_classification,
R.id.cls_state});
// I shouldn't have to comment on this one:
setListAdapter(adapter);
// Optional: when the user clicks a list item we
//could do something. However, we will choose
//to do nothing...
final ListView lv = getListView();
lv.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
HashMap<String, String>map = (HashMap<String, String>)parent.getItemAtPosition(position);
String foutname = map.get(TAG_OUTLET_NAME);
String fchannel = map.get(TAG_SPARKLING_CHANNEL);
String fclass = map.get(TAG_SPARKLING_CLASSIFICATION);
String fclass_state = map.get(TAG_CLASS);
Intent i = new Intent(OutletsList.this, GdgScoreSheeet.class);
i.putExtra("outlt", foutname);
i.putExtra("chnl", fchannel);
i.putExtra("cls", fclass);
i.putExtra("clsstate", fclass_state);
startActivity(i);
});
}
public class LoadMathQuestions extends AsyncTask<Void, Void, Boolean> {
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(OutletsList.this);
pDialog.setMessage("Loading outlets please wait...");
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();
}
}
}
Use this code as an example to replace where your Intent is created:
Intent i = new Intent();
// Additional Extras
if(fclass_state.equals("GOLD")){
i.setClass(OutletList.this, GoldActivity.class);
// additional extras
} else if(fclass_state.equals("SILVER")){
i.setClass(OutletList.this, SilverActivity.class);
// additional extras
} else if(fclass_state.equals("BRONZE")){
i.setClass(OutletList.this, BronzeActivity.class);
// additional extras
} else {
i.setClass(OutletList.this, UnassignedActivity.class);
// additional extras
}
In your onClick method:
switch(position) {
// first list item selected
case 0:
Intent i = new Intent(OutletsList.this, GdgScoreSheeet.class);
i.putExtra("outlt", foutname);
i.putExtra("chnl", fchannel);
i.putExtra("cls", fclass);
i.putExtra("clsstate", fclass_state);
startActivity(i);
break;
// second list item selected
case 1:
...
}

Recreate same Listview on item click

I have a Listview and is working well. I'm getting JSON data from remote server and using SimpleAdapter. Basically I get song list from the server. But now, I want to let user select category first. After selecting any category I want to change the URL depending on the selected category, and then populate the listview again. Like, I'm calling getlist.php to get categories. Now if user selects a category named POP, want to call getlist.php?cat=pop to get all pop songs and re-populate the listview where user will see a list of pop songs.
private static String url_json = "http://10.0.2.2/aaa/getlist.php"; //this gives only the categories
private static String url_json = "http://10.0.2.2/aaa/getlist.php?cat=pop"; //this gives all songs those are under category pop
I don't think code is necessary here, if you still need please tell me, I'll update with code given.
Till now I used the following code in onItemClick but not working:
categorySelected = true;
url_json += "?c=Bangla";
new LoadAllProducts().execute();
lv.invalidateViews(); //final ListView lv = getListView();
So, let me summerise the full thing. On category item click, I want to change the URL I'm getting data from, and refresh the Listview with new data. Thanks in advance.
Code: Please have a look at my code and suggest any change.
public class AllRBT extends ListActivity {
// Progress Dialog
private ProgressDialog pDialog;
ArrayList<HashMap<String, String>> productsList;
// url to get all products list
//private static String url_all_products = "http://aloashbei.com.bd/vasonapps/getList.php";
private static String url_all_products = "http://10.0.2.2/aaa/getlist.php";
private static Boolean categorySelected = false;
private static String confTitle = "Confirmation needed !";
private static String confBody = "We want to send message from next time you select any ring back tone. This may cost 15 taka by your network operator.";
// JSON Node names
private static final String TAG_SUCCESS = "success";
private static final String TAG_PRODUCTS = "rbts";
private static final String TAG_PID = "code";
private static final String TAG_NAME = "name";
private static final String TAG_ARTIST = "artist";
private String mobileNumber = "";
// products JSONArray
JSONArray products = null;
private EditText inputSearch;
SimpleAdapter adapter;
//ListAdapter adapter;
///////////////////////////////////////////////////////////////////////////////////////////////////
private void getMobileNumber(){
AlertDialog.Builder alert = new AlertDialog.Builder(this);
alert.setTitle(confTitle);
alert.setMessage(confBody);//Are you sure want to buy this ring back tones?
// Set an EditText view to get user input
//final EditText input = new EditText(this);
//alert.setView(input);
alert.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
//String m = input.getText().toString();
// Do something with value!
mobileNumber = "017";
}
});
alert.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
// Canceled.
mobileNumber = "";
}
});
alert.show();
}
public String[] generateMessage(String number, int code){
String opCode = number.substring(0, 3);
String messageBody = "", destination = "";
String[] returnValue;
if(opCode.equals("015")){
messageBody = "TT "+code;
destination = "5000";
}else if(opCode.equals("017")){
messageBody = "WT "+code;
destination = "4000";
}else if(opCode.equals("019")){
messageBody = ""+code;
destination = "2222";
}else if(opCode.equals("016")){
messageBody = "CT "+code;
destination = "3123";
}else if(opCode.equals("018")){
messageBody = "GET "+code;
destination = "8466";
}else if(opCode.equals("011")){
messageBody = "Get"+code;
destination = "9999";
}else{
messageBody = "Invalid number";
}
return new String[] {messageBody, destination};
}
private void sendMessage(String dest, String body, String popupText){
if(popupText != "")
Toast.makeText(getApplicationContext(), popupText, Toast.LENGTH_LONG).show();
SmsManager smsManager = SmsManager.getDefault();
smsManager.sendTextMessage(dest, null, body, null, null);
}
///////////////////////////////////////////////////////////////////////////////////////////////////
#Override
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_all_rbt);
//setContentView(R.layout.activity_all_rbt);
//filterText = (EditText) findViewById(R.id.search_box);
//filterText.addTextChangedListener(filterTextWatcher);
//setListAdapter(new ArrayAdapter<String>(this,
//android.R.layout.list_content,
//getStringArrayList());
// Hashmap for ListView
productsList = new ArrayList<HashMap<String, String>>();
//filter listView
inputSearch = (EditText) findViewById(R.id.inputSearch);
inputSearch.addTextChangedListener(new TextWatcher() {
#Override
public void onTextChanged(CharSequence cs, int arg1, int arg2, int arg3){
// When user changed the Text
AllRBT.this.adapter.getFilter().filter(cs);
}
#Override
public void beforeTextChanged(CharSequence arg0, int arg1, int arg2, int arg3) {
}
#Override
public void afterTextChanged(Editable arg0) {
}
});
// Loading products in Background Thread
new LoadAllProducts().execute();
// Get listview
final ListView lv = getListView();
// on seleting single product
// launching Edit Product Screen
lv.setOnItemClickListener(new OnItemClickListener(){
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id){
//lv.invalidateViews();
//if(false){
categorySelected = true;
url_all_products += "?c=Bangla";
new LoadAllProducts().execute();
lv.invalidateViews();
//}
//Context context = getApplicationContext();
String[] values;
// getting values from selected ListItem
String pid = ((TextView) view.findViewById(R.id.pid)).getText().toString();
if(mobileNumber == ""){
getMobileNumber();
return;
}
values = generateMessage(mobileNumber, Integer.parseInt(pid));
String popup = "Sending message '"+values[0]+"' to "+values[1];
sendMessage(values[1], values[0], popup);
//Toast toast = Toast.makeText(context, msg, Toast.LENGTH_SHORT);
//toast.show();
}
});
}
// Response from Edit Product Activity
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
// if result code 100
if (resultCode == 100) {
// if result code 100 is received
// means user edited/deleted product
// reload this screen again
Intent intent = getIntent();
finish();
startActivity(intent);
}
}
/**
* Background Async Task to Load all product by making HTTP Request
* */
class LoadAllProducts extends AsyncTask<String, String, String> {
/**
* Before starting background thread Show Progress Dialog
* */
#Override
protected void onPreExecute(){
super.onPreExecute();
pDialog = new ProgressDialog(AllRBT.this);
pDialog.setMessage("Loading ring back tones. Please wait...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(false);
pDialog.show();
}
/**
* getting All products from url
* */
protected String doInBackground(String... args) {
// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
// getting JSON string from URL
//Toast toast = Toast.makeText(getApplicationContext(), "text", Toast.LENGTH_LONG);
//toast.show();
JSONParser jParser = new JSONParser();
JSONObject json = jParser.makeHttpRequest(url_all_products, "GET", params);
// Check your log cat for JSON reponse
//Log.d("All Products: ", json.toString());
try {
// Checking for SUCCESS TAG
int success = 1;//json.getInt(TAG_SUCCESS);
if (success == 1){
// products found
// Getting Array of Products
products = json.getJSONArray(TAG_PRODUCTS);
// looping through All Products
for (int i = 0; i < products.length(); i++) {
JSONObject c = products.getJSONObject(i);
// Storing each json item in variable
String id = c.getString(TAG_PID);
String name = c.getString(TAG_NAME);
String artist = c.getString(TAG_ARTIST);
// creating new HashMap
HashMap<String, String> map = new HashMap<String, String>();
// adding each child node to HashMap key => value
map.put(TAG_PID, id);
map.put(TAG_NAME, name);
map.put(TAG_ARTIST, artist);
// adding HashList to ArrayList
productsList.add(map);
}
} else {
// no products found
// Launch Add New product Activity
//Intent i = new Intent(getApplicationContext(),
// NewProductActivity.class);
// Closing all previous activities
//i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
//startActivity(i);
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
/**
* After completing background task Dismiss the progress dialog
* **/
protected void onPostExecute(String file_url) {
// dismiss the dialog after getting all products
pDialog.dismiss();
// updating UI from Background Thread
runOnUiThread(new Runnable() {
public void run() {
/**
* Updating parsed JSON data into ListView
* */
AllRBT.this.adapter = new SimpleAdapter(
AllRBT.this, productsList,
R.layout.list_item, new String[] { TAG_PID, TAG_NAME, TAG_ARTIST}, new int[] { R.id.pid, R.id.name, R.id.artist });
// updating listview
setListAdapter(adapter);
}
});
}
}
}
Judging from the (very minimal) few lines of code you've provided you are loading stuff into your List that is backing your ListView from an AsyncTask (LoadAllProducts?). If that is the case, be sure to update your ListView's data in the onPostExecute() method you should override, and call something like notifyDataSetChanged() when you finished updating.
For more info on how to use AsyncTasks, check the great number of answers on this topic on SO. For instance, I put an answer with some info on AsyncTasks here: progress dialog is not displaying in async task when asynctask is called from separate class
Update after code was added:
OK, I never used a ListActivity before, but after reading some documentation I think the problem is that calling setListAdapter() a second time will not refresh the ListView (as was mentioned here). Instead of creating a new SimpleAdapter every time I think you should update your productList (clear it, add to it, whatever you want) and then call AllRBT.this.adapter.notifyDataSetChanged(). This should trigger the ListView to re-fetch the data from your adapter, which by now contains your new data.
Also some other remarks that will make your code cleaner:
you need not call runOnUiThread() from onPostExecute(), since onPostExecute() is guaranteed to run on the main thread already (as per AsyncTask contract).
I think you don't need to add an OnItemClickListener by yourself. It seems that a ListActivity already does that for you and you can instead simply override its onListItemClick() method.

java.lang.NullPointerException AllSuggestionsActivity.onTextChanged (AllSuggestionsActivity.this.adapter.getFilter().filter(cs);)

I am getting an error (java.lang.NullPointerException) when I execute the code for the ListView with EditText for filtering at the line
AllSuggestionsActivity.this.adapter.getFilter().filter(cs);
kindly help.
public class AllSuggestionsActivity extends ListActivity {
EditText inputSearch;
ListView lstList;
// Progress Dialog
private ProgressDialog pDialog;
ArrayAdapter<String> adapter = null;
// Creating JSON Parser object
JSONParser jParser = new JSONParser();
ArrayList<HashMap<String, String>> suggestionsList;
// url to get all suggestions list
private static String url_all_suggestions = "http://10.0.2.2/JKUAT-M-SUGGESTION-BOX/get_all_suggestions.php";
// JSON Node names
private static final String TAG_SUCCESS = "success";
private static final String TAG_SUGGESTIONS = "suggestions";
private static final String TAG_SID = "sid";
private static final String TAG_SUBJECT = "subject";
// suggestions JSONArray
JSONArray suggestions = null;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.all_suggestions);
inputSearch = (EditText) findViewById(R.id.inputSearch);
lstList = (ListView) findViewById(android.R.id.list);
// Hashmap for ListView
suggestionsList = new ArrayList<HashMap<String, String>>();
// Loading suggestions in Background Thread
new LoadAllSuggestions().execute();
// Get listview
ListView lv = getListView();
/**
* Enabling Search Filter
* */
inputSearch.addTextChangedListener(new TextWatcher() {
#Override
public void onTextChanged(CharSequence cs, int arg1, int arg2, int arg3) {
// When user changed the Text
AllSuggestionsActivity.this.adapter.getFilter().filter(cs);
}
#Override
public void beforeTextChanged(CharSequence arg0, int arg1, int arg2,
int arg3) {
// TODO Auto-generated method stub
}
#Override
public void afterTextChanged(Editable arg0) {
// TODO Auto-generated method stub
}
});
// on seleting single suggestion
// launching Edit Suggestion Screen
lv.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// getting values from selected ListItem
String sid = ((TextView) view.findViewById(R.id.sid)).getText()
.toString();
// Starting new intent
Intent in = new Intent(getApplicationContext(),
EditSuggestionActivity.class);
// sending sid to next activity
in.putExtra(TAG_SID, sid);
// starting new activity and expecting some response back
startActivityForResult(in, 100);
}
});
}
// Response from Edit Suggestion Activity
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
// if result code 100
if (resultCode == 100) {
// if result code 100 is received
// means user edited/deleted suggestion
// reload this screen again
Intent intent = getIntent();
finish();
startActivity(intent);
}
}
/**
* Background Async Task to Load all suggestion by making HTTP Request
* */
class LoadAllSuggestions extends AsyncTask<String, String, String> {
/**
* Before starting background thread Show Progress Dialog
* */
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(AllSuggestionsActivity.this);
pDialog.setMessage("Loading all suggestions. Please wait.......");
pDialog.setIndeterminate(false);
pDialog.setCancelable(false);
pDialog.show();
}
/**
* getting All suggestions from url
* */
#Override
protected String doInBackground(String... args) {
// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
// getting JSON string from URL
JSONObject json = jParser.makeHttpRequest(url_all_suggestions,
"GET", params);
// Check your log cat for JSON reponse
Log.d("All Suggestions: ", json.toString());
try {
// Checking for SUCCESS TAG
int success = json.getInt(TAG_SUCCESS);
if (success == 1) {
// suggestions found
// Getting Array of Suggestions
suggestions = json.getJSONArray(TAG_SUGGESTIONS);
// looping through All Suggestions
for (int i = 0; i < suggestions.length(); i++) {
JSONObject c = suggestions.getJSONObject(i);
// Storing each json item in variable
String id = c.getString(TAG_SID);
String subject = c.getString(TAG_SUBJECT);
// creating new HashMap
HashMap<String, String> map = new HashMap<String, String>();
// adding each child node to HashMap key => value
map.put(TAG_SID, id);
map.put(TAG_SUBJECT, subject);
// adding HashList to ArrayList
suggestionsList.add(map);
}
} else {
// no suggestions found
Intent i = new Intent(getApplicationContext(),
MainScreenActivity.class);
// Closing all previous activities
i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(i);
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
/**
* After completing background task Dismiss the progress dialog
* **/
#Override
protected void onPostExecute(String file_url) {
// dismiss the dialog after getting all suggestions
pDialog.dismiss();
// updating UI from Background Thread
runOnUiThread(new Runnable() {
#Override
public void run() {
/**
* Updating parsed JSON data into ListView
* */
ListAdapter adapter = new SimpleAdapter(
AllSuggestionsActivity.this, suggestionsList,
R.layout.list_item, new String[] { TAG_SID,
TAG_SUBJECT }, new int[] { R.id.sid,
R.id.subject });
// updating listview
setListAdapter(adapter);
}
});
}
}
}
xml code for the listview:
<?xml version="1.0" encoding="utf-8"?>
<ScrollView
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:fillViewport="true">
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical">
<EditText
android:id="#+id/inputSearch"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="5dp"
android:ems="10"
android:maxLines="1"
android:hint="Search" >
<requestFocus />
</EditText>-->
<!-- Main ListView
Always give id value as list(#android:id/list)
-->
<ListView
android:id="#android:id/list"
android:layout_width="fill_parent"
android:layout_height="wrap_content"/>
</LinearLayout>
enter code here
</ScrollView>
You've initialized your adapter to null & never re-initialized it with real values. So when the line executes AllSuggestionsActivity.this.adapter.getFilter().filter(cs) the part in bold is where the NullPointerException is being thrown.
ArrayAdapter<String> adapter = null;
Also, it looks like your adapter depends on some JSON data, if thats the case & your trying to have filter options for that data, you could set the text watcher for your edit text in onPostExecute() after your adapter has the data ready.
Finally, you should get rid of runOnUiThread in your onPostExecute(). The onPostExecute() runs on the main UI thread by default so there is no need for runOnUiThread to be there.
Kindly find solution to the error:
public class AllSuggestionsActivity extends ListActivity {
SimpleAdapter adapter;
EditText inputSearch;
// Progress Dialog
private ProgressDialog pDialog;
// Creating JSON Parser object
JSONParser jParser = new JSONParser();
ArrayList<HashMap<String, String>> suggestionsList;
// url to get all suggestions list
private static String url_all_suggestions = "http://10.0.2.2/JKUAT-M-SUGGESTION-BOX/get_all_suggestions.php";
// JSON Node names
private static final String TAG_SUCCESS = "success";
private static final String TAG_SUGGESTIONS = "suggestions";
private static final String TAG_SID = "sid";
private static final String TAG_SUBJECT = "subject";
// suggestions JSONArray
JSONArray suggestions = null;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.all_suggestions);
// Hashmap for ListView
suggestionsList = new ArrayList<HashMap<String, String>>();
// Loading suggestions in Background Thread
new LoadAllSuggestions().execute();
// Get listview
ListView lv = getListView();
// on seleting single suggestion
// launching Edit Suggestion Screen
lv.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// getting values from selected ListItem
String sid = ((TextView) view.findViewById(R.id.sid)).getText()
.toString();
// Starting new intent
Intent in = new Intent(getApplicationContext(),
EditSuggestionActivity.class);
// sending sid to next activity
in.putExtra(TAG_SID, sid);
// starting new activity and expecting some response back
startActivityForResult(in, 100);
}
});
}
// Response from Edit Suggestion Activity
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
// if result code 100
if (resultCode == 100) {
// if result code 100 is received
// means user edited/deleted suggestion
// reload this screen again
Intent intent = getIntent();
finish();
startActivity(intent);
}
}
/**
* Background Async Task to Load all suggestion by making HTTP Request
* */
class LoadAllSuggestions extends AsyncTask<String, String, String> {
/**
* Before starting background thread Show Progress Dialog
* */
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(AllSuggestionsActivity.this);
pDialog.setMessage("Loading all suggestions. Please wait.......");
pDialog.setIndeterminate(false);
pDialog.setCancelable(false);
pDialog.show();
}
/**
* getting All suggestions from url
* */
#Override
protected String doInBackground(String... args) {
// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
// getting JSON string from URL
JSONObject json = jParser.makeHttpRequest(url_all_suggestions,
"GET", params);
// Check your log cat for JSON reponse
Log.d("All Suggestions: ", json.toString());
try {
// Checking for SUCCESS TAG
int success = json.getInt(TAG_SUCCESS);
if (success == 1) {
// suggestions found
// Getting Array of Suggestions
suggestions = json.getJSONArray(TAG_SUGGESTIONS);
// looping through All Suggestions
for (int i = 0; i < suggestions.length(); i++) {
JSONObject c = suggestions.getJSONObject(i);
// Storing each json item in variable
String id = c.getString(TAG_SID);
String subject = c.getString(TAG_SUBJECT);
// creating new HashMap
HashMap<String, String> map = new HashMap<String, String>();
// adding each child node to HashMap key => value
map.put(TAG_SID, id);
map.put(TAG_SUBJECT, subject);
// adding HashList to ArrayList
suggestionsList.add(map);
}
} else {
// no suggestions found
Intent i = new Intent(getApplicationContext(),
MainScreenActivity.class);
// Closing all previous activities
i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(i);
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
/**
* After completing background task Dismiss the progress dialog
* **/
#Override
protected void onPostExecute(String file_url) {
// dismiss the dialog after getting all suggestions
pDialog.dismiss();
// updating UI from Background Thread
runOnUiThread(new Runnable() {
#Override
public void run() {
/**
* Updating parsed JSON data into ListView
* */
adapter = new SimpleAdapter(
AllSuggestionsActivity.this, suggestionsList,
R.layout.list_item, new String[] { TAG_SID,
TAG_SUBJECT }, new int[] { R.id.sid,
R.id.subject });
// updating listview
setListAdapter(adapter);
/**
* Enabling Search Filter
* */
inputSearch = (EditText) findViewById(R.id.inputSearch);
inputSearch.addTextChangedListener(new TextWatcher() {
#Override
public void onTextChanged(CharSequence cs, int arg1, int arg2, int arg3) {
// When user changed the Text
AllSuggestionsActivity.this.adapter.getFilter().filter(cs);
}
#Override
public void beforeTextChanged(CharSequence arg0, int arg1, int arg2,
int arg3) {
// TODO Auto-generated method stub
}
#Override
public void afterTextChanged(Editable arg0) {
// TODO Auto-generated method stub
}
});
}
});
}
}
}
xml file remains intact

Search result displayed twice in list view

I would like to display the data from MySql in a listview using a search parameter in my application.
I've succeeded, but the problem I'm having is that every time I push the search button twice, both sets of result data are shown in the ListView, whereas I only want to display the latest set of results.
This is the code I'm using:
public class ListPerusahaan extends ListActivity {
/** Called when the activity is first created. */
private static final String TAG_ID = "id";
private static final String TAG_NAMA = "nama_perusahaan";
private static final String TAG_PEKERJAAN = "pekerjaan";
private static final String TAG_ALAMAT= "alamat";
private static final String TAG_DEADLINE = "deadline";
EditText keyword; Button search; private ProgressDialog pDialog; ArrayList<HashMap<String, String>> DataList; // JSONArray perusahaan = null;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.listperusahaan);
keyword=(EditText)findViewById(R.id.Editsearch);
search=(Button)findViewById(R.id.search);
DataList = new ArrayList<HashMap<String, String>>();
search.setOnClickListener(new View.OnClickListener()
{
#Override public void onClick(View v) {
// TODO Auto-generated method stub
if (keyword.getText().toString().length() == 0 ) {
Toast toast = Toast.makeText(getApplicationContext(),"Please enter your keyword", Toast.LENGTH_SHORT);
toast.setGravity(Gravity.CENTER_VERTICAL|Gravity.CENTER_HORIZONTAL, 0, 0);
toast.show();
}
else {
new searchData().execute();
}
}
});
}
#SuppressLint("NewApi") public class searchData extends AsyncTask<Void, Void, Void>
{
/**
* Before starting background thread Show Progress Dialog
* */
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(ListPerusahaan.this);
pDialog.setMessage("Loading ...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(false);
pDialog.show();
}
#Override
protected Void doInBackground(Void... params) {
// TODO Auto-generated method stub
// ArrayList<HashMap<String, String>> mylist = new ArrayList<HashMap<String, String>>();
List<NameValuePair> paramemeter = new ArrayList<NameValuePair>();
paramemeter.add(new BasicNameValuePair("keyword", keyword.getText().toString()));
JSONObject json = JSONParser.getJSONFromUrl("http://10.0.2.2/appmysql/dataperusahaan.php", paramemeter);
try{
JSONArray perusahaan = json.getJSONArray("perusahaan");
if (perusahaan != null)
{
for(int i=0;i<perusahaan.length();i++){
// HashMap<String, String> map1 = new HashMap<String, String>();
JSONObject jsonobj = perusahaan.getJSONObject(i);
// Storing each json item in variable
String id = jsonobj.getString(TAG_ID);
String nama_perusahaan = jsonobj.getString(TAG_NAMA);
String pekerjaan = jsonobj.getString(TAG_PEKERJAAN);
String alamat = jsonobj.getString(TAG_ALAMAT);
String deadline = jsonobj.getString(TAG_DEADLINE);
// creating new HashMap
HashMap<String, String> map1 = new HashMap<String, String>();
// adding each child node to HashMap key => value
map1.put(TAG_ID, id);
map1.put(TAG_NAMA, nama_perusahaan);
map1.put(TAG_PEKERJAAN, pekerjaan);
map1.put(TAG_ALAMAT, alamat);
map1.put(TAG_DEADLINE, deadline);
// adding HashList to ArrayList
DataList.add(map1);
}
}
else {
Toast toast= Toast.makeText(getApplicationContext(), "No data found", Toast.LENGTH_SHORT);
toast.setGravity(Gravity.CENTER_VERTICAL|Gravity.CENTER_HORIZONTAL, 0, 0);
toast.show();
}
}
catch(JSONException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void result) {
// TODO Auto-generated method stub
pDialog.dismiss();
// updating UI from Background Thread
runOnUiThread(new Runnable() {
public void run() {
/**
* Updating parsed JSON data into ListView
* */
ListAdapter adapter = new SimpleAdapter(
ListPerusahaan.this, DataList,R.layout.row,
new String[] { TAG_NAMA, TAG_PEKERJAAN, TAG_ALAMAT, TAG_DEADLINE },
new int[] { R.id.nama_perusahaan, R.id.pekerjaan, R.id.alamat,R.id.deadline});
// updating listview
setListAdapter(adapter);
final ListView lv = getListView();
lv.setTextFilterEnabled(true);
lv.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
/*
#SuppressWarnings("unchecked")
HashMap<String, String> o = (HashMap<String, String>) lv.getItemAtPosition(position);
Toast.makeText(ListPerusahaan.this, "Perusahaan '" + o.get("nama_perusahaan") + "' was clicked.", Toast.LENGTH_SHORT).show();
*/
// getting values from selected ListItem
String nama = ((TextView) view.findViewById(R.id.nama_perusahaan)).getText().toString();
String pekerjaan = ((TextView) view.findViewById(R.id.pekerjaan)).getText().toString();
String alamat = ((TextView) view.findViewById(R.id.alamat)).getText().toString();
String deadline = ((TextView) view.findViewById(R.id.deadline)).getText().toString();
// Starting new intent
Intent in = new Intent(getApplicationContext(), detail_lowongan.class);
in.putExtra(TAG_NAMA, nama);
in.putExtra(TAG_PEKERJAAN, pekerjaan);
in.putExtra(TAG_ALAMAT, alamat);
in.putExtra(TAG_DEADLINE, deadline);
startActivity(in);
}
});
}
});
}
}
}
Edit: in onclick clear DataList
search.setOnClickListener(){
......
DataList.clear(); //in onclick method
}
I am not sure whether you are looking for this or not...but if you don't want to allow duplicates in your list try ....
When the data filled in your list
Set<type> set=new Hashset(yourlist);
ArrayList<type> nodupList=new ArrayList<type>();
noduplist.addAll(set);
using this way it will remove the duplicates in your list
Edit:
Try this
After for loop
Set<HashMap> set=new HashSet(DataList);
ArrayList<HashMap> nodupList=new ArrayList<HashMap>();
nodupList.addAll(set);
DataList.clear();
DataList.addAll(nodupList);
try it may help you
Clear the DataList of the ArrayList type before populating it in the for loop.

Categories

Resources