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.
Related
I working on an Android project which has a ListView and contains one TextView to display the contact and contact are stored in my website in form of json.
json link for contacts
I am able to parse the contacts I have no problem with that. But the problem is the parsed data is displayed as a number like "776057619" in the TextView and I want this TextView number to be taken and stored in a separate variable. By doing this I can use it to prompt the user "weather you want to call that particular number"??. But I don't no how to pull that number from the TextView to a separate variable and use to call inside ListView's OnItemClickListener
below is my code
public class Contactmedia extends ListActivity {
private ProgressDialog pDialog;
JSONParser jsonParser = new JSONParser();
private static final String READ_CONTACT_URL = "http://www.iamnotcrazy.hol.es/webservice/contact.php";
private static final String TAG_NUMBER ="number";
private static final String TAG_POSTS = "posts";
private JSONArray mid = null;
//manages all of our comments in a list.
private ArrayList<HashMap<String, String>> mContactList;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.contactmedialist);
}
#Override
protected void onResume() {
super.onResume();
new LoadComments().execute();
}
/**
* Retrieves json data of comments
*/
public void updateJSONdata() {
mContactList = new ArrayList<HashMap<String, String>>();
JSONParser jParser = new JSONParser();
JSONObject json = jParser.getJSONFromUrl(READ_CONTACT_URL);
try {
mid= json.getJSONArray(TAG_POSTS);
for (int i = 0; i < mid.length(); i++) {
JSONObject c = mid.getJSONObject(i);
String number = c.getString(TAG_NUMBER);
HashMap<String, String> map = new HashMap<String, String>();
map.put(TAG_NUMBER, number);
mContactList.add(map);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
/**
* Inserts the parsed data into our listview
*/
private void updateList() {
ListAdapter adapter = new SimpleAdapter(this, mContactList,
R.layout.contactmediadesign, new String[] { TAG_NUMBER
}, new int[] { R.id.contactno
});
setListAdapter(adapter);
ListView lv = getListView();
lv.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
/* this is where i have problem how to get that number without converting to string*/
TextView v = (TextView)view.findViewById(R.id.contactno);
int myNum = Integer.parseInt(v.getText().toString());
/* and here i want use that mynum after getiing phonenumber for calling purpouse ass shown below
* but its not working :(*/
if (position == 0){
Toast.makeText(getApplicationContext(), "yes you done it!!", Toast.LENGTH_SHORT).show();
Intent callIntent = new Intent(Intent.ACTION_CALL);
callIntent.setData(Uri.parse("tel:"+"myNum"));
startActivity(callIntent);
}
}
});
}
public class LoadComments extends AsyncTask<Void, Void, Boolean> {
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(Contactmedia.this);
pDialog.setMessage("Loading complaints...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
#Override
protected Boolean doInBackground(Void... arg0) {
updateJSONdata();
return null;
}
#Override
protected void onPostExecute(Boolean result) {
super.onPostExecute(result);
pDialog.dismiss();
updateList();
}
}
}
Since you actually need string, you don't have to convert to integer at all:
TextView v = (TextView)view.findViewById(R.id.contactno);
...
callIntent.setData(Uri.parse("tel:"+ v.getText().toString()));
or if you do need to store that number in variable for some reason, you should use String instead
TextView v = (TextView)view.findViewById(R.id.contactno);
string myNum = v.getText().toString();
...
callIntent.setData(Uri.parse("tel:" + myNum));
I would recommend getting the data associated with that position rather than trying to parse the view to get it.
You can get the data from the adapter with adapter.getItem(int pos). Just make adapter final or a member variable to access it in the OnItemClickListener.
First of all you should check your Manifest file, you should have this outside the "application" tag but within the "manifest" tag:
<uses-permission android:name="android.permission.CALL_PHONE" />
Try to do something like this in your code:
Intent callIntent = new Intent(Intent.ACTION_CALL, Uri.parse("tel:" + v.getText().toString()));
startActivity(callIntent);
You should use String value instead of int
remove the double quotation on mynum. you can also use basic oop to save your integer value. fyi, myNum doesnt have to be an integer. it can be a string
ListView lv = getListView();
lv.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
/* this is where i have problem how to get that number without converting to string*/
TextView v = (TextView)view.findViewById(R.id.contactno);
int myNum = Integer.parseInt(v.getText().toString());
setNumber(myNum); //saving the myNum variable
System.out.println("number is: " + getNumber());//if you want to get the value of myNum, just call the getNumber()
if (position == 0){
Toast.makeText(getApplicationContext(), "yes you done it!!", Toast.LENGTH_SHORT).show();
Intent callIntent = new Intent(Intent.ACTION_CALL);
callIntent.setData(Uri.parse("tel:"+ myNum));//remove the quotation for myNum
startActivity(callIntent);
}
}
private int number;
void setNumber(int number){
this.number=number;
}
int getNumber(){
return number;
}
i want to have a search bar that searches a number that has been typed in (for example: 115048) and put that in a listview. the json file looks like this http://api.ccapp.it/v1/student/115048/schedule/11
hope someone can help me, the code that i use right now to search a link is like this but it doesnt have a search bar:
public class RoosterviewMd extends ListActivity {
Button mButton;
EditText mEdit;
private ProgressDialog pDialog;
// URL to get contacts JSON
//private static String id = null;
//private static String url = "http://api.ccapp.it/v1/student/" + id + "/schedule/11";
private static String url = "http://api.ccapp.it/v1/student/115048/schedule/12";
// JSON Node names
private static final String TAG_LESSON = "class";
private static final String TAG_ROOM = "room";
private static final String TAG_TEACHER = "teacher";
// contacts JSONArray
JSONArray contacts = null;
// Hashmap for ListView
ArrayList<HashMap<String, String>> contactList;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.roosterviewmd);
//Number input
final EditText input = (EditText) findViewById(R.id.editText2);
//buttons for all the days
Button btn2 = (Button) findViewById(R.id.button29);
btn2.setOnClickListener(new View.OnClickListener() {
public void onClick(View v)
{
Toast.makeText(getBaseContext(), "Je ziet je rooster voor maandag al" , Toast.LENGTH_SHORT ).show();
}
});
Button btnOne = (Button)findViewById(R.id.button30);
btnOne.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
Intent intent = new Intent(getApplicationContext(), RoosterviewDi.class);
startActivity(intent);
}
});
Button btnTwo = (Button)findViewById(R.id.button31);
btnTwo.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
Intent intent = new Intent(getApplicationContext(), RoosterviewWo.class);
startActivity(intent);
}
});
Button btnThree = (Button)findViewById(R.id.button32);
btnThree.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
Intent intent = new Intent(getApplicationContext(), RoosterviewDo.class);
startActivity(intent);
}
});
Button btnFour = (Button)findViewById(R.id.button33);
btnFour.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
Intent intent = new Intent(getApplicationContext(), RoosterviewVr.class);
startActivity(intent);
}
});
//Buttons end here
contactList = new ArrayList<HashMap<String, String>>();
ListView lv = getListView();
// Listview on item click listener
lv.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// getting values from selected ListItem
String lesson = ((TextView) view.findViewById(R.id.lesson))
.getText().toString();
String teacher = ((TextView) view.findViewById(R.id.teacher))
.getText().toString();
String room = ((TextView) view.findViewById(R.id.room))
.getText().toString();
}
});
// Calling async task to get json
new GetContacts().execute();
}
/**
* Async task class to get json by making HTTP call
* */
private class GetContacts extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
// Showing progress dialog
pDialog = new ProgressDialog(RoosterviewMd.this);
pDialog.setMessage("Give me a second please");
pDialog.setCancelable(false);
pDialog.show();
}
#Override
protected Void doInBackground(Void... arg0) {
// Creating service handler class instance
ServiceHandler sh = new ServiceHandler();
// Making a request to url and getting response
String jsonStr = sh.makeServiceCall(url, ServiceHandler.GET);
Log.d("Response: ", "> " + jsonStr);
if (jsonStr != null) {
try {
JSONObject jsonObj = new JSONObject(jsonStr);
JSONArray arr1 = jsonObj.getJSONArray("lessons");
JSONArray arr2 = arr1.getJSONArray(0); //Dag
for (int b = 0; b < arr2.length(); b++) {
JSONObject c = arr2.getJSONObject(b);
String lesson = c.getString(TAG_LESSON);
String teacher = c.getString(TAG_TEACHER);
String room = c.getString(TAG_ROOM);
// tmp hashmap for single contact
HashMap<String, String> contact = new HashMap<String, String>();
// adding each child node to HashMap key => value
contact.put(TAG_LESSON, lesson);
contact.put(TAG_TEACHER, teacher);
contact.put(TAG_ROOM, room);
// adding contact to contact list
contactList.add(contact);
}
} catch (JSONException e) {
e.printStackTrace();
}
} else {
Log.e("CCApp", "Couldn't get any data from the url");
Toast.makeText(getBaseContext(),"We are aware of this error and are working on it, in the mean time eat a cookie", Toast.LENGTH_LONG).show();
}
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
// Dismiss the progress dialog
if (pDialog.isShowing())
pDialog.dismiss();
/**
* Updating parsed JSON data into ListView
* */
ListAdapter adapter = new SimpleAdapter(RoosterviewMd.this, contactList,
R.layout.list_item, new String[] {TAG_LESSON, TAG_TEACHER,
TAG_ROOM }, new int[] { R.id.lesson,
R.id.teacher, R.id.room });
setListAdapter(adapter);
}
}
}
i hope someone can help me with this
Check out this answer: Get text from web page to string
Basically, you can simply get the text from the page and pass it into a string, and search the string application side for the contents of your edit text.
If you're looking for more functionality with the data from the web site, I would pull the Json into an array of Jsonobjects using something like Gson. You'd then be able to use the data from the web page in a bit more of a structured manner.
Edit: Now to actually answer your question.
You can include an edit text and button in your xml in order to search using a basic search bar kinda thing.
To set a listener on the button, you would do something like:
findViewById(R.id.button).setOnClickListener(new OnClickListener(){
#Override
protected void onClick(View v){
//Here, we can control what the response to the button press is, and grab the text in the edit text field.
String editTextString = findViewById(R.id.edittext).getEditableText().toString();
//Now we have a string used to parse the json or whatever else you need to do.
//May want to add a case here if editTextString is null to prevent runtime errors.
}
}
(Forgive me if there's any minor syntatic errors, just wrote that up quick here in the browser, no API to check on it. :))
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:
...
}
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
i am currently doing a page which retrieve data from php server and now trying to retrieve and image from drawable by using setImageResource but is not working, i dunno what wrong with it and is it possible for me to just save image name in database then retrieve image by using image name?
beside that, i try to do a simple plus minus button for quantity but the apps force stop once i click on the button..
public class FoodDetailActivity extends Activity
{
TextView FoodName;
TextView FoodDesc;
TextView FoodPrice;
ImageView FoodImg;
EditText Number;
Button plus;
Button minus;
Button Addcart;
String fid;
int number;
// Progress Dialog
private ProgressDialog pDialog;
// JSON parser class
JSONParser jsonParser = new JSONParser();
// single product url
private static final String url_food_details = "http://10.0.2.2/android_user/FoodDetail.php";
// JSON Node names
private static final String TAG_SUCCESS = "success";
private static final String TAG_FOOD = "food";
private static final String TAG_FID = "fid";
private static final String TAG_FOODNAME = "food_name";
private static final String TAG_FOODPRICE = "food_price";
private static final String TAG_FOODDESCRIPTION = "food_description";
private static final String TAG_FOODURL = "food_url";
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_food_detail);
// button
plus = (Button)findViewById(R.id.btn_plus);
plus.setOnClickListener(increase);
minus = (Button)findViewById(R.id.btn_minus);
minus.setOnClickListener(decrease);
Addcart = (Button)findViewById(R.id.btn_submit);
Number = (EditText)findViewById(R.id.text_number);
// getting food details from intent
Intent i = getIntent();
// getting food id (fid) from intent
fid = i.getStringExtra(TAG_FID);
// Getting complete product details in background thread
new GetFoodDetails().execute();
}
// Increase number of quantity
private OnClickListener increase = new OnClickListener()
{
public void onClick(View v)
{
String quantity = Number.getText().toString().trim();
number = Integer.parseInt(quantity);
if(number > 0 && number < 99)
{
number = number + 1;
Number.setText(Integer.toString(number));
}
else if(number == 99)
{
number = 1;
Number.setText(Integer.toString(number));
}
}
};
// Decrease number of quantity
private OnClickListener decrease = new OnClickListener()
{
public void onClick(View v)
{
String quantity = Number.getText().toString();
number = Integer.valueOf(quantity);
if(number > 1 && number <= 99)
{
number = number - 1;
Number.setText(Integer.toString(number));
}
else if(number == 1)
{
number = 99;
Number.setText(Integer.toString(number));
}
}
};
class GetFoodDetails extends AsyncTask<String, String, String>
{
/**
* Before starting background thread Show Progress Dialog
* */
#Override
protected void onPreExecute()
{
super.onPreExecute();
pDialog = new ProgressDialog(FoodDetailActivity.this);
pDialog.setMessage("Loading food details. Please wait...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
/**
* Getting product details in background thread
* */
protected String doInBackground(String... params)
{
// updating UI from Background Thread
runOnUiThread(new Runnable()
{
public void run()
{
// Check for success tag
int success;
try {
// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("fid", fid));
// getting product details by making HTTP request
// Note that product details url will use GET request
JSONObject json = JSONParser.makeHttpRequest(url_food_details, "GET", params);
// check your log for json response
Log.d("Single Food Details", json.toString());
// json success tag
success = json.getInt(TAG_SUCCESS);
if (success == 1)
{
// successfully received food details
JSONArray foodObj = json.getJSONArray(TAG_FOOD); // JSON Array
// get first product object from JSON Array
JSONObject food = foodObj.getJSONObject(0);
// Loader image - will be shown before loading image
int loader = R.drawable.loader;
String image_url = food.getString(TAG_FOODURL);
// product with this fid found
// Edit Text
FoodName = (TextView)findViewById(R.id.food_name);
FoodPrice = (TextView)findViewById(R.id.food_price);
FoodDesc = (TextView)findViewById(R.id.food_desc);
FoodImg = (ImageView)findViewById(R.id.img_food);
// display product data in EditText
FoodName.setText(food.getString(TAG_FOODNAME));
FoodPrice.setText("RM" + food.getString(TAG_FOODPRICE));
FoodDesc.setText(food.getString(TAG_FOODDESCRIPTION));
// ImageLoader class instance
ImageLoader imgLoader = new ImageLoader(getApplicationContext());
// display image
imgLoader.DisplayImage(image_url, loader, FoodImg);
}
else
{
// no food detail found
// Launch error message
AlertDialog.Builder ad = new AlertDialog.Builder(FoodDetailActivity.this);
ad.setTitle("Error");
ad.setMessage("Food Detail is empty!");
ad.setPositiveButton("OK", new DialogInterface.OnClickListener()
{
public void onClick(DialogInterface dialoginterface, int i)
{
}
});
ad.show();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
});
return null;
}
protected void onPostExecute(String file_url)
{
// dismiss the dialog once got all details
pDialog.dismiss();
}
}
}
The problem had been solve, i using the ImageLoader retrieve image at server side with url store in database.
In here:
Drawable d = getResources().getDrawable(R.drawable.mcchicken); //<<<<
you are trying to use context of Activity before onCreate call. move Drawable d initialization inside onCreate method of Activity after setContentView as:
Drawable d; //<<< declare d here
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_food_detail);
d = getResources().getDrawable(R.drawable.mcchicken); //<< initialize d here
....
}
Edit : : inside doInBackground method you are trying to access UI element. instead of updating UI from doInBackground using runOnUiThread. you will need to move all UI related code in onPostExecute which call on Ui thread after doInBackground execution complete.
In your code is much messy material. So nicely from the beginning. First is only question.
Why you are putting inside doInBackground() method runOnUiThread()? If you want to update your UI with some information from task running in background, for this you have onProgressUpdate() or onPostExecute() method which are synchronized with UI Thread and allow its updates. doInBackground() method is directly designated for background processing and you shouldn't broke it.
Then this line:
if (food.getString(TAG_FOODNAME) == "McChicken")
will always return false because you are comparing references and not values. Always you are comparing strings, you have to use equals() method that makes a trick.
And last thing is this:
Drawable d = getResources().getDrawable(R.drawable.mcchicken);
You can't call that before setContentView() is called. Reason is that main purpose of setContentView() is that it creates all instances of UI elements and resources and if you something that requires resources call before this method, always you will get NPE