I currently have this class below which parses json urls and loads images and texts into a listview with the help of the Lazy Adapter Class and background thread.
Each list item consists of an image view and 2 text views.
I want to create pop up boxes (alert dialog) for each of the generated list items. The alert dialog will have options which will call other applications.
My question :
Would it be wise to code this alert dialog functionality in this class? I'm worried that there is a lot of stuff currently being done in the background and it might affect the app's functionality.
If not could anyone suggest another way to do it. thanks.
Json Activity Class :
public class JsonActivity extends SherlockActivity{
private ProgressDialog progressDialog;
// JSON Node names
static final String TAG_NAME = "name";
static final String TAG_IMAGEURL = "imageurl";
ListView list;
LazyAdapter adapter;
String chartUrl;
String[] urlNames = new String[] {
"urls..."
};
// chartItemList is the array list that holds the chart items
ArrayList<HashMap<String, String>> chartItemList = new ArrayList<HashMap<String,
String>>();
//Holds imageurls
ArrayList<String> imageurls = new ArrayList<String>();
JsonParser Parser = new JsonParser();
// JSONArray
JSONArray chartItems = null;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.chart);
//Get the bundle
Bundle bundle = getIntent().getExtras();
//Extract the data from the bundle
int chartIndex = bundle.getInt("chartIndex");
String chartUrl = urlNames[chartIndex];
setTitle(bundle.getString("chartname"));
//url from where the JSON has to be retrieved
String url = chartUrl;
//Check if the user has a connection
ConnectivityManager cm = (ConnectivityManager)
getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo info = cm.getActiveNetworkInfo();
if (info != null) {
if (!info.isConnected()) {
Toast.makeText(this, "Please check your connection and try again.",
Toast.LENGTH_SHORT).show();
}
//if positive, fetch the articles in background
else new getChartItems().execute(chartUrl);
}
//else show toast
else {
Toast.makeText(this, "Please check your connection and try again.",
Toast.LENGTH_SHORT).show();
}
}
class getChartItems extends AsyncTask<String, String, String> {
// Shows a progress dialog while setting up the background task
#Override
protected void onPreExecute() {
super.onPreExecute();
progressDialog = new ProgressDialog(JsonActivity.this);
progressDialog.setMessage("Loading chart...");
progressDialog.setIndeterminate(false);
progressDialog.setCancelable(false);
progressDialog.show();
}
//Gets the json data for chart items data and presents it in a list view
#Override
protected String doInBackground(String... args) {
String json = Parser.getJSONFromUrl(args[0]);
String imageurl;
String rank;
String name;
String url;
try{
chartItems = new JSONArray(json);
JSONObject json_data=null;
for(int i=0;i<chartItems.length();i++){
json_data = chartItems.getJSONObject(i);
//Retrieves the value of the name from the json object
name=json_data.getString("name");
//Retrieves the image url for that object and adds it to an arraylist
imageurl=json_data.getString("imageurl");
//imageurls.add(imageurl);
HashMap<String, String> hashMap = new HashMap<String, String>();
// adding each child node to HashMap key => value
//hashMap.put(TAG_RANK, rank);
hashMap.put(TAG_NAME, name);
hashMap.put(TAG_IMAGEURL, imageurl);
// adding HashMap to ArrayList
chartItemList.add(hashMap);
}
;
}
catch (JSONException e) {
e.printStackTrace();
}
runOnUiThread(new Runnable() {
public void run() {
list=(ListView)findViewById(R.id.list);
// Getting adapter by passing xml data ArrayList
adapter = new LazyAdapter(JsonActivity.this, chartItemList);
list.setAdapter(adapter);
// Click event for single list row
list.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
}
});
}
});
return null;
}
//Removes the progress dialog when the data has been fetched
protected void onPostExecute(String args) {
progressDialog.dismiss();
}
}
}
My answer for this is Yes, it is wise enough to implement one more level network communication as far as your use case justifies it.
This depends on communication channel (EDGE/ 3G/ 4G/ WiFi) and use case of the application. Technically it is pretty much possible as far as you are doing this in background. It also depends on the size of the list which you are loading. Best way to check this is by implementing plug-able code and try it out.
Related
I am working on android ListView and i am getting one issue.I created one list view into the XML file installation.xml and i want to use that list view into my Searchdata.java. so basically what i want that when i click on searchdata button than data is fetched from web service and after parsing, it will saved into the listview.and when i click on Installation View button than new window will be appear where i could see that list data.
SearchData.java
public class SearchData extends Activity {
EditText Keyword;
JSONParser jsonparser = new JSONParser();
ListView Datalist;
HorizontalScrollView VideoDatalist;
ArrayList<HashMap<String, String>> DataList;
ArrayList<HashMap<String, String>> VideoDataList;
JSONArray contacts = null;
private ProgressDialog pDialog;
ImageButton searchdata,InstallationView;
String Keyvalue = new String();
private static final String TAG_InnerText = "InnerText";
private static final String TAG_Title = "Title";
private static final String TAG_URL = "URL";
private static final String TAG_VIDEO_URL = "URL";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_search_data);
InstallationView=(ImageButton)findViewById(R.id.InstallationView);
Keyword = (EditText) findViewById(R.id.KeyData);
Datalist=(ListView)findViewById(R.layout.activity_installation);
VideoDatalist=(HorizontalScrollView)findViewById(R.id.Horizontallist);
searchdata=(ImageButton)findViewById(R.id.searchicon);
String Keyvalue = new String();
DataList = new ArrayList<HashMap<String, String>>();
VideoDataList = new ArrayList<HashMap<String, String>>();
searchdata.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
new ReadData().execute();
}
});
InstallationView.setOnClickListener(new View.OnClickListener(){
public void onClick(View v)
{
startActivity(new Intent(SearchData.this, Installation.class));
}
});
}
public class ReadData extends AsyncTask<Void, Void, Void>
{
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(SearchData.this);
pDialog.setMessage("Please wait...");
pDialog.setCancelable(false);
pDialog.show();
}
protected Void doInBackground(Void... arg0) {
try{
Keyvalue=Keyword.getText().toString();
String Jsonstr = jsonparser.makeHttpRequest("http://10.47.93.26:8080/Search/api/Search/"+Keyvalue);
try {
if (Jsonstr != null) {
JSONArray jsonObj = new JSONArray (Jsonstr);
for (int i = 0; i < jsonObj.length(); i++) {
JSONObject c = jsonObj.getJSONObject(i);
String name = c.optString(TAG_Title);
String url = c.optString(TAG_URL);
HashMap<String, String> info = new HashMap<String, String>();
if( !name.isEmpty() )
{
info.put(TAG_Title, name);
}
else
{
info.put(TAG_Title,"User Manual");
}
if(url.contains("youtube"))
{
info.put(TAG_URL, url);
VideoDataList.add(info);
}
else
{
info.put(TAG_URL, url);
DataList.add(info);
}
}
}
else {
Log.e("ServiceHandler", "Couldn't get any data from the url");
}
}
catch (JSONException e) {
e.printStackTrace();
}
}
catch(Exception ex)
{
ex.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
if (pDialog.isShowing())
pDialog.dismiss();
SimpleAdapter adapter = new SimpleAdapter(
SearchData.this, DataList,
R.layout.list_item, new String[]
{
TAG_Title
}, new int[] {
R.id.InnerText });
Datalist.setAdapter(adapter);
}
}
}
web service running and parsing code is running correctly. i am getting error at post method,so can you help me on this.
Error
Call your Installation activity in onClick() method:
And pass your ArrayList data through intent,
InstallationView.setOnClickListener(new View.OnClickListener(){
public void onClick(View v)
{
Intent intent= new Intent(SearchData.this, Installation.class);
intent.putParcelableArrayListExtra("HASH_MAP",DataList);
startActivity(intent);
}
});
In your Installation activity class,set the view in onCreate() and initialize listview from xml file:
setContentView(R.layout.activity_installation);
ListView listView = (ListView)findViwById(R.id.listview);
And try to get the data from intent:
ArrayList<HashMap<String,String>> hashmap_dataList = getIntent.getParcelableArrayListExtra("HASH_MAP");
then do whatever you want with listview and hashmap.
In the onCreate(...) method of your SearchData Activity, the following can never work and will always return 'null' (hence your NullPointerException)...
Datalist=(ListView)findViewById(R.layout.activity_installation);
Calling findViewById(...) will only work for any UI elements which have been inflated when you called setContentView(...). In this case you used R.layout.activity_search_data for your layout file which doesn't contain a ListView with an id of R.layout.activity_installation which is, by the way, a resource id of a layout file and not a resource id of a UI element.
The only way you can do what you need is to put your data as an extra into the Intent you use when you call...
startActivity(new Intent(SearchData.this, Installation.class));
...when the Installation Activity is created it will then need to get the data and create its own adapter.
EDIT: HashMap is Serializable and can be passed as an Intent extra. Pass your DataList HashMap as follows...
Intent i = new Intent(SearchData.this, Installation.class);
i.putExtra("data_list", DataList);
startActivity(i);
In the Installation Activity you can then use...
getIntent().getSerializableExtra("data_list");
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 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.
I have this ListView which fetches its data (image+text) from JSON on the web.
Now I have a task to make the ListView is accessible without internet connection. My idea is by saving the JSON data from the web when the app is run for the first time with internet, and when it can't find internet connection it will get the data from the persistent Storage.
Can anybody help me with this? I'm still a beginner can't find the example of SharedPreferences with JSON.
Thanks a lot
public class ProjectsList extends Activity {
/** Called when the activity is first created. */
//ListView that will hold our items references back to main.xml
ListView lstTest;
//Array Adapter that will hold our ArrayList and display the items on the ListView
ProjectAdapter arrayAdapter;
//List that will host our items and allow us to modify that array adapter
ArrayList<Project> prjcts=null;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.projects_list);
//Initialize ListView
lstTest= (ListView)findViewById(R.id.lstText);
//Initialize our ArrayList
prjcts = new ArrayList<Project>();
//Initialize our array adapter notice how it references the listitems.xml layout
arrayAdapter = new ProjectAdapter(ProjectsList.this, R.layout.listitems,prjcts,ProjectsList.this);
//Set the above adapter as the adapter of choice for our list
//lstTest.setAdapter(arrayAdapter);
lstTest.setAdapter(arrayAdapter);
if (isOnline())
{
//Instantiate the Web Service Class with he URL of the web service not that you must pass
WebService webService = new WebService("http://liebenwald.spendino.net/admanager/dev/android/projects.json");
//Pass the parameters if needed , if not then pass dummy one as follows
Map<String, String> params = new HashMap<String, String>();
params.put("var", "");
//Get JSON response from server the "" are where the method name would normally go if needed example
// webService.webGet("getMoreAllerts", params);
String response = webService.webGet("", params);
try
{
//Parse Response into our object
Type collectionType = new TypeToken<ArrayList<Project>>(){}.getType();
//JSON expects an list so can't use our ArrayList from the lstart
List<Project> lst= new Gson().fromJson(response, collectionType);
//Now that we have that list lets add it to the ArrayList which will hold our items.
for(Project l : lst)
{
prjcts.add(l);
ConstantData.projectsList.add(l);
}
//Since we've modified the arrayList we now need to notify the adapter that
//its data has changed so that it updates the UI
arrayAdapter.notifyDataSetChanged();
}
catch(Exception e)
{
Log.d("Error: ", e.getMessage());
}
}
lstTest.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Intent care = new Intent(ProjectsList.this, ProjectDetail.class);
care.putExtra("spendino.de.ProjectDetail.position",position);
startActivity(care);
}
});
}
#Override
public void onDestroy()
{
yAdapter.imageLoader.stopThread();
lstTest.setAdapter(null);
super.onDestroy();
}
protected boolean isOnline() {
ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo netInfo = cm.getActiveNetworkInfo();
if (netInfo != null && netInfo.isConnected()) {
return true;
} else {
AlertDialog.Builder alertbox = new AlertDialog.Builder(this);
alertbox.setTitle("spendino Helfomat");
alertbox.setMessage ("Please check your internet connection");
alertbox.setPositiveButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
//Main.this.finish();
}
});
alertbox.show();
return false;
}
}
}
SharedPreferences has no methods for saving a JSON object as is, you must try to convert it to a String. Then when getting it you must parse this String back to JSON. Good luck!
JSON to String:
JSONObject o = new JSONObject(data.trim());
String name = o.getString(Constants.NAME);
long date = o.getLong(Constants.DATE);
String mes = o.getString(Constants.MESSAGE);
StringBuilder buf = new StringBuilder(text.getText());
buf.append(name).append(" (").append(dfTime.format(new Date(date))).append(")\n").append(mes).append("\n");
text.setText(buf.toString());
Making a JSON from a String is not a harder task, use StringTokenizer. Good luck!