I am trying to populate my listview from this API.
There are no errors when I compile and run the app, but there is just a blank MainActivity. Here is my code for my project.
Main Activity:
package com.example.szen95.meddict;
import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.view.MenuItem;
public class MainActivity extends ActionBarActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if (savedInstanceState == null) {
getSupportFragmentManager().beginTransaction()
.add(R.id.container, new SearchFragment())
.commit();
}
getSupportActionBar().setElevation(0f);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
SearchFragment:
package com.example.szen95.meddict;
/**
* Created by szen95 on 6/15/15.
*/
import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.SimpleAdapter;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.HashMap;
/**
* A placeholder fragment containing a simple view.
*/
public class SearchFragment extends Fragment {
private ProgressDialog pDialog;
// URL to get contacts JSON
private static String url = "http://dailymed.nlm.nih.gov/dailymed/services/v2/drugclasses.json";
// JSON Node names
private static final String TAG_DATA = "data";
private static final String TAG_CODE = "code";
private static final String TAG_CODING_SYSTEM = "codingSystem";
private static final String TAG_TYPE = "type";
private static final String TAG_NAME = "name";
// contacts JSONArray
JSONArray data = null;
// ArrayAdapter<String> mConditionsAdapter;
public SearchFragment() {
}
ArrayList<HashMap<String, String>> dataList = new ArrayList<HashMap<String, String>>();
public View onCreateView(LayoutInflater inflater,
ViewGroup container,
Bundle savedInstanceState) {
// Retrieving the currently selected item number
// int position = getArguments().getInt("position");
// Creating view correspoding to the fragment
View v = inflater.inflate(R.layout.fragment_main, container, false);
new GetData().execute();
return v;
}
/**
* Async task class to get json by making HTTP call
* */
private class GetData extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
// Showing progress dialog
pDialog = new ProgressDialog(getActivity());
//
pDialog.setMessage("Please wait...");
pDialog.setCancelable(false);
pDialog.show();
}
#Override
protected Void doInBackground(Void... arg0) {
// Creating service handler class instance
ServiceHandler sh = new ServiceHandler();
// Making a request to url and getting response
String jsonStr = sh.makeServiceCall(url, ServiceHandler.GET);
Log.d("Response: ", "> " + jsonStr);
if (jsonStr != null) {
try {
JSONObject jsonObj = new JSONObject(jsonStr);
// Getting JSON Array node
data = jsonObj.getJSONArray(TAG_DATA);
// looping through All Contacts
for (int i = 0; i < data.length(); i++) {
JSONObject c = data.getJSONObject(i);
String code = c.getString(TAG_CODE);
String codingSystem = c.getString(TAG_CODING_SYSTEM);
String type = c.getString(TAG_TYPE);
String name = c.getString(TAG_NAME);
// tmp hashmap for single contact
HashMap<String, String> data = new HashMap<String, String>();
// adding each child node to HashMap key => value
data.put(TAG_CODE, code);
data.put(TAG_CODING_SYSTEM, codingSystem);
data.put(TAG_TYPE, type);
data.put(TAG_NAME, name);
// adding contact to contact list
dataList.add(data);
}
} catch (JSONException e) {
e.printStackTrace();
}
} else {
Log.e("ServiceHandler", "Couldn't get any data from the url");
}
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
// Dismiss the progress dialog
if (pDialog.isShowing())
pDialog.dismiss();
/**
* Updating parsed JSON data into ListView
* */
SimpleAdapter adapter = new SimpleAdapter(getActivity(), dataList,
R.layout.list_item_search, new String[] { TAG_NAME, TAG_CODE}, new int[] { R.id.name,
R.id.code});
setListAdapter(adapter);
}
}
private void setListAdapter(SimpleAdapter adapter) {
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setHasOptionsMenu(true);
}
#Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
inflater.inflate(R.menu.menu_main, menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.action_refresh) {
// FetchDataTask defTask = new FetchDataTask();
// defTask.execute();
return true;
}
return super.onOptionsItemSelected(item);
}
}
Below two things will fix your problem -
Extend your fragment by ListFragment not with Fragment.
Delete below method.
private void setListAdapter(SimpleAdapter adapter) {
}
Related
I am inflating the menu from JSON which contain its name and id. I had written Fragment5 which is used to be calling an URL for JSON. In that url I want to call the id of the menu.
This is my code. The code is running fine if I am commenting the two line
String scat = menu_nms.get(0);
int cat = Integer.parseInt(scat);
MainActivity.java
package com.latrodealz.wowwdealz;
import android.app.Fragment;
import android.app.FragmentManager;
import android.app.FragmentTransaction;
import android.app.ProgressDialog;
import android.app.SearchManager;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.SearchView;
import android.widget.Toast;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonArrayRequest;
import com.android.volley.toolbox.Volley;
import com.google.android.gms.appindexing.Action;
import com.google.android.gms.appindexing.AppIndex;
import com.google.android.gms.common.api.GoogleApiClient;
import com.latrodealz.wowwdealz.adapter.SlidingMenuAdapter;
import com.latrodealz.wowwdealz.fragment.Fragment1;
import com.latrodealz.wowwdealz.fragment.Fragment2;
import com.latrodealz.wowwdealz.fragment.Fragment3;
import com.latrodealz.wowwdealz.fragment.Fragment4;
import com.latrodealz.wowwdealz.fragment.Fragment5;
import com.latrodealz.wowwdealz.model.ItemSlideMenu;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.List;
/**
* Created by NgocTri on 10/18/2015.
*/
public class MainActivity extends AppCompatActivity {
private List<ItemSlideMenu> listSliding;
private SlidingMenuAdapter adapter;
private ListView listViewSliding;
private DrawerLayout drawerLayout;
private ActionBarDrawerToggle actionBarDrawerToggle;
//Web api url
public static final String MENU_URL = "http://69.89.31.191/~webtech6/android_wow/menu_dtls.php";
//Tag values to read from json
public static final String MENU_ID = "menu_id";
public static final String MENU_NM = "menu_nm";
//ArrayList for Storing menu ids and names
private ArrayList<String> menu_ids;
private ArrayList<String> menu_nms;
/**
* ATTENTION: This was auto-generated to implement the App Indexing API.
* See https://g.co/AppIndexing/AndroidStudio for more information.
*/
private GoogleApiClient client;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
menu_ids = new ArrayList<>();
menu_nms = new ArrayList<>();
//Calling the getMenuData method
getMenuData();
//Init component
listViewSliding = (ListView) findViewById(R.id.lv_sliding_menu);
drawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
listSliding = new ArrayList<>();
//Add item for sliding list
listSliding.add(new ItemSlideMenu(R.drawable.ic_action_settings, "Home"));
adapter = new SlidingMenuAdapter(this, listSliding);
listViewSliding.setAdapter(adapter);
//Display icon to open/ close sliding list
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
//Set title
setTitle(listSliding.get(0).getTitle());
//item selected
listViewSliding.setItemChecked(0, true);
//Close menu
drawerLayout.closeDrawer(listViewSliding);
//Display fragment 1 when start
replaceFragment(0);
//Handle on item click
listViewSliding.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
//Set title
setTitle(listSliding.get(position).getTitle());
//item selected
listViewSliding.setItemChecked(position, true);
//Replace fragment
replaceFragment(position);
//Close menu
drawerLayout.closeDrawer(listViewSliding);
}
});
actionBarDrawerToggle = new ActionBarDrawerToggle(this, drawerLayout, R.string.drawer_opened, R.string.drawer_closed) {
#Override
public void onDrawerOpened(View drawerView) {
super.onDrawerOpened(drawerView);
invalidateOptionsMenu();
}
#Override
public void onDrawerClosed(View drawerView) {
super.onDrawerClosed(drawerView);
invalidateOptionsMenu();
}
};
drawerLayout.addDrawerListener(actionBarDrawerToggle);
// ATTENTION: This was auto-generated to implement the App Indexing API.
// See https://g.co/AppIndexing/AndroidStudio for more information.
client = new GoogleApiClient.Builder(this).addApi(AppIndex.API).build();
}
private void getMenuData() {
//Showing a progress dialog while our app fetches the data from url
final ProgressDialog loading = ProgressDialog.show(this, "Please wait...", "Fetching data...", false, false);
//Creating a json array request to get the json from our api
JsonArrayRequest jsonArrayRequest = new JsonArrayRequest(MENU_URL,
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
//Dismissing the progressdialog on response
loading.dismiss();
//Displaying our grid
showMenu(response);
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
}
);
//Creating a request queue
RequestQueue requestQueue = Volley.newRequestQueue(this);
//Adding our request to the queue
requestQueue.add(jsonArrayRequest);
}
private void showMenu(JSONArray jsonArray) {
//Looping through all the elements of json array
for (int i = 0; i < jsonArray.length(); i++) {
//Creating a json object of the current index
JSONObject obj = null;
try {
//getting json object from current index
obj = jsonArray.getJSONObject(i);
//getting menuid and menuname from json object
menu_ids.add(obj.getString(MENU_ID));
menu_nms.add(obj.getString(MENU_NM));
} catch (JSONException e) {
e.printStackTrace();
}
}
//Add item for sliding list
for (int i = 0; i < menu_ids.size(); i++) {
listSliding.add(new ItemSlideMenu(R.drawable.ic_action_about, menu_nms.get(i)));
}
adapter = new SlidingMenuAdapter(this, listSliding);
listViewSliding.setAdapter(adapter);
//Add item for sliding list
listSliding.add(new ItemSlideMenu(R.drawable.ic_action_settings, "MY CART"));
listSliding.add(new ItemSlideMenu(R.drawable.ic_action_settings, "MY ACCOUNT"));
listSliding.add(new ItemSlideMenu(R.drawable.ic_action_settings, "MY ORDERS"));
adapter = new SlidingMenuAdapter(this, listSliding);
listViewSliding.setAdapter(adapter);
//Display Array List
// Toast.makeText(getBaseContext(), menu_ids + "", Toast.LENGTH_LONG).show();
// Toast.makeText(getBaseContext(), menu_nms + "", Toast.LENGTH_LONG).show();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main_menu, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if (actionBarDrawerToggle.onOptionsItemSelected(item)) {
return true;
}
switch (item.getItemId()) {
case R.id.action_search:
// User chose the "Settings" item, show the app settings UI...
Intent intent = new Intent(MainActivity.this, SearchableActivity.class);
startActivityForResult(intent, 0);
//Toast.makeText(this, "You have selected Search Search Menu", Toast.LENGTH_SHORT).show();
return true;
case R.id.action_kart:
// User chose the "Favorite" action, mark the current item
// as a favorite...
Toast.makeText(this, "You have selected Search KART Menu", Toast.LENGTH_SHORT).show();
return true;
case R.id.action_notifications:
// User chose the "Favorite" action, mark the current item
// as a favorite...
Toast.makeText(this, "You have selected Search Notifications Menu", Toast.LENGTH_SHORT).show();
return true;
default:
// If we got here, the user's action was not recognized.
// Invoke the superclass to handle it.
return super.onOptionsItemSelected(item);
}
//return super.onOptionsItemSelected(item);
}
#Override
protected void onPostCreate(Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
actionBarDrawerToggle.syncState();
}
/**
* Called when the user clicks the Search Menu
* public void callSearchActivity(View view) {
* Intent intent = new Intent(this, SearchActivity.class);
* startActivity(intent);
* }
*/
//Create method replace fragment
private void replaceFragment(int pos) {
Fragment fragment = null;
int menu_size = menu_ids.size();
String scat = menu_nms.get(0);
int cat = Integer.parseInt(scat);
if (pos == 0) {
fragment = new Fragment1();
} else if (pos > 0 && pos <= menu_size) {
SharedPreferences sharePref = getSharedPreferences("menu_dtls", Context.MODE_PRIVATE);
sharePref.edit().remove("menu_id").commit();
SharedPreferences.Editor editor = sharePref.edit();
editor.putInt("menu_id", pos);
editor.apply();
fragment = new Fragment5();
} else if (pos == (menu_size + 1)) {
fragment = new Fragment2();
} else if (pos == (menu_size + 2)) {
fragment = new Fragment3();
} else if (pos == (menu_size + 3)) {
fragment = new Fragment4();
} else {
fragment = new Fragment1();
}
if (null != fragment) {
FragmentManager fragmentManager = getFragmentManager();
FragmentTransaction transaction = fragmentManager.beginTransaction();
transaction.replace(R.id.main_content, fragment);
transaction.addToBackStack(null);
transaction.commit();
}
}
#Override
public void onStart() {
super.onStart();
// ATTENTION: This was auto-generated to implement the App Indexing API.
// See https://g.co/AppIndexing/AndroidStudio for more information.
client.connect();
Action viewAction = Action.newAction(
Action.TYPE_VIEW, // TODO: choose an action type.
"Main Page", // TODO: Define a title for the content shown.
// TODO: If you have web page content that matches this app activity's content,
// make sure this auto-generated web page URL is correct.
// Otherwise, set the URL to null.
Uri.parse("http://host/path"),
// TODO: Make sure this auto-generated app deep link URI is correct.
Uri.parse("android-app://com.latrodealz.wowwdealz/http/host/path")
);
AppIndex.AppIndexApi.start(client, viewAction);
}
#Override
public void onStop() {
super.onStop();
// ATTENTION: This was auto-generated to implement the App Indexing API.
// See https://g.co/AppIndexing/AndroidStudio for more information.
Action viewAction = Action.newAction(
Action.TYPE_VIEW, // TODO: choose an action type.
"Main Page", // TODO: Define a title for the content shown.
// TODO: If you have web page content that matches this app activity's content,
// make sure this auto-generated web page URL is correct.
// Otherwise, set the URL to null.
Uri.parse("http://host/path"),
// TODO: Make sure this auto-generated app deep link URI is correct.
Uri.parse("android-app://com.latrodealz.wowwdealz/http/host/path")
);
AppIndex.AppIndexApi.end(client, viewAction);
client.disconnect();
}
}
Fragment5.java
package com.latrodealz.wowwdealz.fragment;
import android.app.Fragment;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.SharedPreferences;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.ListView;
import com.latrodealz.wowwdealz.R;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.HashMap;
public class Fragment5 extends Fragment {
JSONObject jsonobject;
JSONArray jsonarray;
ListView listview;
ListViewAdapter adapter;
ProgressDialog mProgressDialog;
ArrayList<HashMap<String, String>> arraylist;
static String RANK = "rank";
static String COUNTRY = "country";
static String POPULATION = "population";
static String FLAG = "flag";
public Fragment5() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment5, container, false);
//TextView menu_id = (TextView)rootView.findViewById(R.id.textid);
//SharedPreferences sharePref = this.getActivity().getSharedPreferences("menu_dtls", Context.MODE_PRIVATE);
//int menuId = sharePref.getInt("menu_id", 0);
// menu_id.setText(String.valueOf(menuId));
ImageView purple=(ImageView)rootView.findViewById(R.id.gridicon);
purple.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
getFragmentManager()
.beginTransaction()
.replace(R.id.main_content, new Fragment4())
.commit();
}
});
new DownloadJSON().execute();
return rootView;
}
// DownloadJSON AsyncTask
private class DownloadJSON extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
// Create a progressdialog
mProgressDialog = new ProgressDialog(getActivity());
// Set progressdialog title
mProgressDialog.setTitle("Fetching data...");
// Set progressdialog message
mProgressDialog.setMessage("Loading...");
mProgressDialog.setIndeterminate(false);
// Show progressdialog
mProgressDialog.show();
}
#Override
protected Void doInBackground(Void... params) {
// Create an array
SharedPreferences sharePref = getActivity().getSharedPreferences("menu_dtls", Context.MODE_PRIVATE);
int menuId = sharePref.getInt("menu_id", 0);
arraylist = new ArrayList<HashMap<String, String>>();
// Retrieve JSON Objects from the given URL address
jsonobject = JSONfunctions
.getJSONfromURL("http://69.89.31.191/~webtech6/android_wow/load.php?catId="+menuId);
try {
// Locate the array name in JSON
jsonarray = jsonobject.getJSONArray("worldpopulation");
for (int i = 0; i < jsonarray.length(); i++) {
HashMap<String, String> map = new HashMap<String, String>();
jsonobject = jsonarray.getJSONObject(i);
// Retrive JSON Objects
map.put("rank", jsonobject.getString("rank"));
map.put("country", jsonobject.getString("country"));
map.put("population", jsonobject.getString("population"));
map.put("flag", jsonobject.getString("flag"));
// Set the JSON Objects into the array
//Toast.makeText(getActivity().getBaseContext(), map + "", Toast.LENGTH_LONG).show();
arraylist.add(map);
}
} catch (JSONException e) {
Log.e("Error", e.getMessage());
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void args) {
// Locate the listview in listview_main.xml
listview = (ListView) getActivity().findViewById(R.id.listview);
// Pass the results into ListViewAdapter.java
adapter = new ListViewAdapter(getActivity(), arraylist);
// Set the adapter to the ListView
listview.setAdapter(adapter);
// Close the progressdialog
mProgressDialog.dismiss();
}
}
}
Perhaps you get exception during JSON parsing. You may surround Integer.parseInt(scat); with try- catch catching ParsingException if Json has no such a field.
But more neat solution is to use GSON with Retrofit, so you can automatically parse you response to java objects, created by jsonschema2pojo.com
i have an activity that list clients on a listview from a sql server database, and i've had implement the searchview.. but i dont know how to implement the query to search the client names from the listview.. can someone help me??
here is my the code from the activity where is the list:
package com.example.hp13_b200.testedesign;
import android.app.ListActivity;
import android.app.ProgressDialog;
import android.app.SearchManager;
import android.content.Context;
import android.content.Intent;
import android.os.AsyncTask;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.support.v7.widget.SearchView;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import org.apache.http.NameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
public class listar_clientes extends ActionBarActivity {
private ListView list;
private TextView nome, abv, esaldo, telefone, mail, morada;
private SearchView search;
private ProgressDialog pDialog;
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.menu_listar_clientes, menu);
// Associate searchable configuration with the SearchView
SearchManager searchManager =
(SearchManager) getSystemService(Context.SEARCH_SERVICE);
SearchView searchView =
(SearchView) menu.findItem(R.id.search).getActionView();
searchView.setSearchableInfo(
searchManager.getSearchableInfo(getComponentName()));
return true;
// Associate searchable configuration with the SearchView
}
// 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://ciemarco.dyndns.org:90/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";
private static final String TAG_SALDO = "esaldo";
private static final String TAG_TELEFONE = "telefone";
private static final String TAG_MORADA = "morada";
private static final String TAG_MAIL = "email";
// products JSONArray
JSONArray products = null;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_listar_clientes);
// Get the intent, verify the action and get the query
Intent intent = getIntent();
/*if (Intent.ACTION_SEARCH.equals(intent.getAction())) {
String query = intent.getStringExtra(SearchManager.QUERY);
doMySearch(query);
}*/
nome = (TextView)findViewById(R.id.name);
abv = (TextView)findViewById(R.id.abv);
telefone = (TextView)findViewById(R.id.telefone);
morada = (TextView)findViewById(R.id.morada);
mail = (TextView)findViewById(R.id.mail);
esaldo = (TextView)findViewById(R.id.esaldo);
list = (ListView)findViewById(android.R.id.list);
// 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
/* list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
// getting values from selected ListItem
String nome = ((TextView) view.findViewById(R.id.name)).getText()
.toString();
Log.d("Cod_conta: ", ""+nome);
// Starting new intent
Intent in = new Intent(listar_clientes.this,
detalhes_cliente.class);
// sending pid to next activity
in.putExtra(TAG_NOME, nome);
//in.putExtra(TAG_ABV, abv);
Log.d("entrou: ", "vai entrar");
//startActivityForResult(in,100);
// starting new activity and expecting some response back
startActivity(in);
}
} );*/
// 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);
String telefone = c.getString(TAG_TELEFONE);
String morada = c.getString(TAG_MORADA);
String mail = c.getString(TAG_MAIL);
String esaldo = c.getString(TAG_SALDO);
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, name);
map.put(TAG_ABV, abv);
map.put(TAG_TELEFONE, telefone);
map.put(TAG_MORADA, morada);
map.put(TAG_MAIL, mail);
map.put(TAG_SALDO, esaldo);
// 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_MAIL, TAG_TELEFONE, TAG_MORADA, TAG_SALDO},
new int[]{R.id.name, R.id.mail, R.id.telefone, R.id.morada, R.id.esaldo});
// updating listview
list.setAdapter(adapter);
}
});
}
}
public void listar(View v){
LinearLayout vwParentRow = (LinearLayout)v.getParent();
TextView nome=(TextView)vwParentRow.getChildAt(1);
TextView telefone=(TextView)vwParentRow.getChildAt(4);
TextView morada=(TextView)vwParentRow.getChildAt(3);
TextView mail=(TextView)vwParentRow.getChildAt(5);
TextView esaldo=(TextView)vwParentRow.getChildAt(6);
// Starting new intent
Intent in = new Intent(getApplicationContext(),
detalhes_cliente.class);
// sending pid to next activity
in.putExtra(TAG_NOME, nome.getText().toString());
in.putExtra(TAG_TELEFONE, telefone.getText().toString());
in.putExtra(TAG_MORADA, morada.getText().toString());
in.putExtra(TAG_MAIL, mail.getText().toString());
in.putExtra(TAG_SALDO, esaldo.getText().toString());
// starting new activity and expecting some response back
startActivityForResult(in, 100);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
public boolean onPrepareOptionsMenu(Menu menu) {
MenuItem item= menu.findItem(R.id.action_settings);
item.setVisible(false);
super.onPrepareOptionsMenu(menu);
return true;
}
}
and here is the code from the searchresultactivity:
package com.example.hp13_b200.testedesign;
import android.app.SearchManager;
import android.content.Intent;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
public class SearchResultsActivity extends ActionBarActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_search_results);
handleIntent(getIntent());
}
#Override
protected void onNewIntent(Intent intent) {
handleIntent(intent);
}
private void handleIntent(Intent intent) {
if (Intent.ACTION_SEARCH.equals(intent.getAction())) {
String query = intent.getStringExtra(SearchManager.QUERY);
//use the query to search your data somehow
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_search_results, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
Regarding the Model-View-Controller approach, all you need to do is create a model with the data that matches your search and hand it tho the view (your list view) that will display it.
You probably want a setOnQueryTextListener which can filter your results when text is written in SearchView.
There is an existing post explaining this quite well, Implementing SearchView in action bar.
I'm new to Android development and I have a problem with setting up getting into the next activity when I click an item in my listview within my ListFragment.
When I compile and run the app, it crashes with the error: Content view not yet created. Here is the relevant code. Any help would be much appreciated!
MainActivity:
package com.example.szen95.meddict;
import android.app.SearchManager;
import android.content.Context;
import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.widget.SearchView;
public class MainActivity extends ActionBarActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if (savedInstanceState == null) {
getSupportFragmentManager().beginTransaction()
.add(R.id.container, new SearchFragment())
.commit();
}
getSupportActionBar().setElevation(0f);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.menu_main, menu);
SearchManager searchManager = (SearchManager) getSystemService( Context.SEARCH_SERVICE );
SearchView searchView = (SearchView) menu.findItem( R.id.search_bar ).getActionView();
searchView.setSearchableInfo( searchManager.getSearchableInfo( getComponentName() ) );
return super.onCreateOptionsMenu(menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
return super.onOptionsItemSelected(item);
}
}
SearchFragment:
package com.example.szen95.meddict;
/**
* Created by szen95 on 6/15/15.
*/
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.ListFragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.HashMap;
/**
* A placeholder fragment containing a simple view.
*/
public class SearchFragment extends ListFragment {
private ProgressDialog pDialog;
// URL to get contacts JSON
private static String url = "http://dailymed.nlm.nih.gov/dailymed/services/v2/drugclasses.json";
// JSON Node names
private static final String TAG_DATA = "data";
private static final String TAG_CODE = "code";
private static final String TAG_CODING_SYSTEM = "codingSystem";
private static final String TAG_TYPE = "type";
private static final String TAG_NAME = "name";
// contacts JSONArray
JSONArray data = null;
// ArrayAdapter<String> mConditionsAdapter;
public SearchFragment() {
}
ArrayList<HashMap<String, String>> dataList;
#Override
public View onCreateView(LayoutInflater inflater,
ViewGroup container,
Bundle savedInstanceState) {
dataList = new ArrayList<HashMap<String, String>>();
// Creating view correspoding to the fragment
View v = inflater.inflate(R.layout.fragment_main, container, false);
ListView lv = getListView();
// Listview on item click listener
lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// getting values from selected ListItem
String name = ((TextView) view.findViewById(R.id.name))
.getText().toString();
String code = ((TextView) view.findViewById(R.id.code))
.getText().toString();
// Starting single contact activity
Intent in = new Intent(getActivity().getApplicationContext(),
Details.class);
in.putExtra(TAG_NAME, name);
in.putExtra(TAG_CODE, code);
startActivity(in);
}
});
new GetData().execute();
return v;
}
/**
* Async task class to get json by making HTTP call
* */
private class GetData extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
// Showing progress dialog
pDialog = new ProgressDialog(getActivity());
//
pDialog.setMessage("Please wait...");
pDialog.setCancelable(false);
pDialog.show();
}
#Override
protected Void doInBackground(Void... arg0) {
// Creating service handler class instance
ServiceHandler sh = new ServiceHandler();
// Making a request to url and getting response
String jsonStr = sh.makeServiceCall(url, ServiceHandler.GET);
Log.d("Response: ", "> " + jsonStr);
if (jsonStr != null) {
try {
JSONObject jsonObj = new JSONObject(jsonStr);
// Getting JSON Array node
data = jsonObj.getJSONArray(TAG_DATA);
// looping through All Contacts
for (int i = 0; i < data.length(); i++) {
JSONObject c = data.getJSONObject(i);
String code = c.getString(TAG_CODE);
String codingSystem = c.getString(TAG_CODING_SYSTEM);
String type = c.getString(TAG_TYPE);
String name = c.getString(TAG_NAME);
// tmp hashmap for single contact
HashMap<String, String> data = new HashMap<String, String>();
// adding each child node to HashMap key => value
data.put(TAG_CODE, code);
data.put(TAG_CODING_SYSTEM, codingSystem);
data.put(TAG_TYPE, type);
data.put(TAG_NAME, name);
// adding contact to contact list
dataList.add(data);
}
} catch (JSONException e) {
e.printStackTrace();
}
} else {
Log.e("ServiceHandler", "Couldn't get any data from the url");
}
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
// Dismiss the progress dialog
if (pDialog.isShowing())
pDialog.dismiss();
/**
* Updating parsed JSON data into ListView
* */
SimpleAdapter adapter = new SimpleAdapter(getActivity(), dataList,
R.layout.list_item_search, new String[] { TAG_NAME, TAG_CODE}, new int[] { R.id.name,
R.id.code});
setListAdapter(adapter);
}
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setHasOptionsMenu(true);
}
//
// #Override
// public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
// inflater.inflate(R.menu.menu_main, menu);
//
//
// }
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.action_about) {
// FetchDataTask defTask = new FetchDataTask();
// defTask.execute();
return true;
}
return super.onOptionsItemSelected(item);
}
}
Details:
package com.example.szen95.meddict;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.view.Menu;
import android.view.MenuInflater;
import android.widget.TextView;
public class Details extends ActionBarActivity {
// JSON node keys
private static final String TAG_NAME = "name";
private static final String TAG_CODE = "code";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_details);
// getting intent data
Intent in = getIntent();
// Get JSON values from previous intent
String name = in.getStringExtra(TAG_NAME);
String code = in.getStringExtra(TAG_CODE);
// Displaying all values on the screen
TextView lblName = (TextView) findViewById(R.id.name_label);
TextView lblCode = (TextView) findViewById(R.id.code_label);
lblName.setText(name);
lblCode.setText(code);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.menu_main, menu);
return onCreateOptionsMenu(menu);
}
}
SearchFragment extends ListFragment. In a ListFragment, getListView() cannot be called in onCreateView(), because onCreateView() is creating the fragment's content view and has not yet completed. The call to getListView() in SearchFragment is the cause of the exception.
Move the the call to getListView() and related to code to one of the fragment lifecycle methods that is called after onCreateView(), such as onViewCreated() or onActivityCreate(). For example:
#Override
public void onViewCreated(View view, Bundle savedInstanceState) {
ListView lv = getListView();
// Listview on item click listener
lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// getting values from selected ListItem
String name = ((TextView) view.findViewById(R.id.name))
.getText().toString();
String code = ((TextView) view.findViewById(R.id.code))
.getText().toString();
// Starting single contact activity
Intent in = new Intent(getActivity().getApplicationContext(),
Details.class);
in.putExtra(TAG_NAME, name);
in.putExtra(TAG_CODE, code);
startActivity(in);
}
});
}
I am getting data from this API and have parsed it into a listview within a fragment. However, I can't seem to get it displayed on the Main Activity. Can anyone point me in the right direction please?
EDIT1: The layout files can be found here.
Main Activity:
package com.example.szen95.meddict;
import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.view.Menu;
import android.view.MenuItem;
public class MainActivity extends ActionBarActivity {
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
}
SearchFragment:
package com.example.szen95.meddict;
import android.app.ListFragment;
import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.SimpleAdapter;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.HashMap;
public class SearchFragment extends ListFragment {
//
// #Override
// protected void onCreate(Bundle savedInstanceState) {
// super.onCreate(savedInstanceState);
// setContentView(R.layout.activity_search_fragment);
// if (savedInstanceState == null) {
// getSupportFragmentManager().beginTransaction()
// .add(R.id.container, new SearchFragment())
// .commit();
// }
// }
private ProgressDialog pDialog;
// URL to get contacts JSON
private static String url = "http://dailymed.nlm.nih.gov/dailymed/services/v2/drugclasses.json";
// JSON Node names
private static final String TAG_DATA = "data";
private static final String TAG_CODE = "code";
private static final String TAG_CODING_SYSTEM = "codingsystem";
private static final String TAG_TYPE = "type";
private static final String TAG_NAME = "name";
// contacts JSONArray
JSONArray data = null;
// Hashmap for ListView
ArrayList<HashMap<String, String>> dataList = new ArrayList<HashMap<String, String>>();
public View onCreateView(LayoutInflater inflater,
ViewGroup container,
Bundle savedInstanceState) {
// Retrieving the currently selected item number
int position = getArguments().getInt("position");
// Creating view correspoding to the fragment
View v = inflater.inflate(R.layout.activity_search_fragment, container, false);
// Updating the action bar title
// getActivity().getActionBar().setTitle(options[position]);
// Calling async task to get json
new GetData().execute();
return v;
}
/**
* Async task class to get json by making HTTP call
* */
private class GetData extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
// Showing progress dialog
pDialog = new ProgressDialog(getActivity());
//
pDialog.setMessage("Please wait...");
pDialog.setCancelable(false);
pDialog.show();
}
#Override
protected Void doInBackground(Void... arg0) {
// Creating service handler class instance
ServiceHandler sh = new ServiceHandler();
// Making a request to url and getting response
String jsonStr = sh.makeServiceCall(url, ServiceHandler.GET);
Log.d("Response: ", "> " + jsonStr);
if (jsonStr != null) {
try {
JSONObject jsonObj = new JSONObject(jsonStr);
// Getting JSON Array node
data = jsonObj.getJSONArray(TAG_DATA);
// looping through All Contacts
for (int i = 0; i < data.length(); i++) {
JSONObject c = data.getJSONObject(i);
String code = c.getString(TAG_CODE);
String codingsystem = c.getString(TAG_CODING_SYSTEM);
String type = c.getString(TAG_TYPE);
String name = c.getString(TAG_NAME);
;
// tmp hashmap for single contact
HashMap<String, String> data = new HashMap<String, String>();
// adding each child node to HashMap key => value
data.put(TAG_CODE, code);
data.put(TAG_CODING_SYSTEM, codingsystem);
data.put(TAG_TYPE, type);
data.put(TAG_NAME, name);
// adding contact to contact list
dataList.add(data);
}
} catch (JSONException e) {
e.printStackTrace();
}
} else {
Log.e("ServiceHandler", "Couldn't get any data from the url");
}
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
// Dismiss the progress dialog
if (pDialog.isShowing())
pDialog.dismiss();
/**
* Updating parsed JSON data into ListView
* */
SimpleAdapter adapter = new SimpleAdapter(getActivity(), dataList,
R.layout.list_item, new String[] { TAG_NAME, TAG_CODE}, new int[] { R.id.name,
R.id.code});
setListAdapter(adapter);
}
}
}
Un comment the onCreate method in searchFragment because your fragment is not inflating any layout
Fragments can be put into a layout using FragmentManager.
Add replace onCreate of your MainActivity with following.
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
FragmentManager fragmentManager = getSupportFragmentManager();
FragmentTransaction fts = fragmentManager.beginTransaction();
Fragment fragment = new SearchFragment();
String fragmentTag = "SearchFragment";
fts.add(R.id.main_container, fragment, fragmentTag);
fts.commit();
}
Change your layout_activity_main.xml to following. You don't need a listview here. Just make sure you have a layout container main_container to place your fragment in.
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<FrameLayout android:id="#+id/main_container"
android:layout_width="match_parent"
android:layout_height="match_parent"
>
</FrameLayout>
<!-- 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"
android:divider="#null"/>
-->
</LinearLayout>
I think your problem is caused by Jason parsing.
private static final String TAG_CODING_SYSTEM = "codingSystem";
Jason key is case sensitive. But please try to debug by yourself next time, it's the only way to become a better coder. Cheers!
When the code is run it loads news only of india even after selecting another option in the Settings Menu. Can someone please tell me the error?
Main Activity:
package com.example.user.s;
import android.app.ListActivity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.AsyncTask;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.HashMap;
public class MainActivity extends ListActivity
{
private ProgressDialog pDialog;
// URL to get contacts JSON
private static String url;
public String servername;
private static final String TAG_ARTICLES="articles";
private static final String TAG_PUBLISH_DATE = "publish_date";
private static final String TAG_SOURCE = "source";
private static final String TAG_SUMMARY = "summary";
private static final String TAG_TITLE = "title";
private static final int RESULT_SETTINGS = 1;
JSONArray articles = null;
// Hashmap for ListView
ArrayList<HashMap<String, String>> articleList;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
articleList = new ArrayList<HashMap<String, String>>();
ListView lv = getListView();
// Listview on item click listener
/* // Starting single contact activity
Intent in = new Intent(getApplicationContext(),
SingleContactActivity.class);
in.putExtra(TAG_PUBLISH_DATE, date);
in.putExtra(TAG_SOURCE, source);
in.putExtra(TAG_SUMMARY, desc);
in.putExtra(TAG_TITLE,ttle);
startActivity(in);*/
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.action_settings:
Intent i = new Intent(this, setting.class);
startActivityForResult(i, RESULT_SETTINGS);
break;
}
return true;
}
private void update() {
GetContacts weatherTask = new GetContacts();
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(getApplication());
String location = prefs.getString(getString(R.string.country_preference),
getString(R.string.country_default));
if(location.equals("India"))
url="http://api.feedzilla.com/v1/categories/19/subcategories/888/articles.json?count=10";
else
url="http://api.feedzilla.com/v1/categories/19/subcategories/890/articles.json?count=10";
weatherTask.execute();
}
#Override
public void onStart() {
super.onStart();
update();
}
private class GetContacts extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
// Showing progress dialog
pDialog = new ProgressDialog(MainActivity.this);
pDialog.setMessage("Please wait...");
pDialog.setCancelable(false);
pDialog.show();
}
#Override
protected Void doInBackground(Void... params) {
// Creating service handler class instance
ServiceHandler sh = new ServiceHandler();
// Making a request to url and getting response
String jsonStr = sh.makeServiceCall(url, ServiceHandler.GET);
Log.d("Response: ", "> " + jsonStr);
if (jsonStr != null) {
try {
JSONObject jsonObj = new JSONObject(jsonStr);
// Getting JSON Array node
articles = jsonObj.getJSONArray(TAG_ARTICLES);
// looping through All Contacts
for (int i = 0; i < articles.length(); i++) {
JSONObject c = articles.getJSONObject(i);
String id = c.getString(TAG_PUBLISH_DATE);
String name = c.getString(TAG_SOURCE);
String email = c.getString(TAG_SUMMARY);
String ttle = c.getString(TAG_TITLE);
HashMap<String, String> contact = new HashMap<String, String>();
// adding each child node to HashMap key => value
contact.put(TAG_PUBLISH_DATE, id);
contact.put(TAG_SOURCE, name);
contact.put(TAG_SUMMARY, email);
contact.put(TAG_TITLE, ttle);
// adding contact to contact list
articleList.add(contact);
}
} catch (JSONException e) {
e.printStackTrace();
}
} else {
Log.e("ServiceHandler", "Couldn't get any data from the url");
}
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
// Dismiss the progress dialog
if (pDialog.isShowing())
pDialog.dismiss();
/**
* Updating parsed JSON data into ListView
* */
ListAdapter adapter = new SimpleAdapter(
MainActivity.this, articleList,
R.layout.row, new String[]{TAG_PUBLISH_DATE, TAG_SOURCE,
TAG_SUMMARY}, new int[]{R.id.publish_date,
R.id.src, R.id.summary});
setListAdapter(adapter);
}
}
}
Settings Activity:
package com.example.user.s;
import android.os.Bundle;
import android.preference.PreferenceActivity;
public class setting extends PreferenceActivity {
private static final String COUNTRIES = "countries";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.preference);
}
}
preference.xml
<?xml version="1.0" encoding="utf-8"?>
<PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android">
<PreferenceCategory
android:title="Country">
<ListPreference
android:key="country_preference"
android:title="#string/country_preference"
android:summary="Choose your Country"
android:entries="#array/entries_transport_list_preference"
android:entryValues="#array/entryvalues_transport_list_preference"
/>
</PreferenceCategory>
</PreferenceScreen>
array.xml:
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string-array name="entries_transport_list_preference">
<item>India</item>
<item>China</item>
<item>Japan</item>
</string-array>
<string-array name="entryvalues_transport_list_preference">
<item>India</item>
<item>China</item>
<item>3</item>
</string-array>``
</resources>
You should call update() in onResume instead onStart
#Override
public void onResume() {
super.onResume();
update();
}