I have made a json android application, to show the reference of the photos, in a list view, but it gives me an error
my code is\
package com.example.jsonapp;
import java.util.ArrayList;
import java.util.HashMap;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.Activity;
import android.app.ListActivity;
import android.app.ProgressDialog;
import android.content.Context;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.Menu;
import android.widget.ListAdapter;
import android.widget.SimpleAdapter;
public class MainActivity extends ListActivity {
// url to make request
private static String url = "https://maps.googleapis.com/maps/api/place/nearbysearch /json?location=mylatandlong&radius=5000&types=restaurant&sensor=false&key=myownkey";
// JSON Node names
private static final String TAG_RESULTS = "results";
private static final String TAG_PHOTOS = "photos";
private static final String TAG_REFRENCE = "photo_reference";
JSONArray results = null;
JSONArray photos = null;
Context c;
// Progress dialog
ProgressDialog pDialog;
ArrayList<HashMap<String, String>> contactList;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
new LaodPhotos().execute(TAG_REFRENCE);
//ListView lv = getListView();
}//the end of on create
public class LaodPhotos extends AsyncTask<String, String, String>{
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(MainActivity.this);
pDialog.setMessage("Loading profile ...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(false);
pDialog.show();
}
#Override
protected String doInBackground(String... arg0) {
contactList = new ArrayList<HashMap<String, String>>();
JSONParser jParser = new JSONParser();
JSONObject json = jParser.getJSONFromUrl(url);
try{
results = json.getJSONArray(TAG_RESULTS);
photos = json.getJSONArray(TAG_PHOTOS);
for(int i=0; i<results.length(); i++){
JSONObject c = results.getJSONObject(i);
if(c != null){
for(int j=0; j<photos.length(); j++){
JSONObject pc = photos.getJSONObject(j);
String photo = pc.getString(TAG_REFRENCE);
// creating new HashMap
HashMap<String, String> map = new HashMap<String, String>();
map.put(TAG_REFRENCE, photo);
contactList.add(map);
}
}
}
}catch(JSONException e){
e.printStackTrace();
}
return null;
}
#Override
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() {
ListAdapter adapter = new SimpleAdapter(c, contactList, R.layout.list_item,
new String[]{TAG_REFRENCE}, new int[]{R.id.photoRef});
setListAdapter(adapter);
}//end of run method
});//end of runOnUiThread
}//end of onPost method
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}
The log cat\
E/AndroidRuntime(23042): java.lang.NullPointerException
E/AndroidRuntime(23042): at android.widget.SimpleAdapter.(SimpleAdapter.java:85)
would any one help me to know how to make this succeed, I want to have the photo_reference
to be able to show it as Image, but first need to know how to have the photo_reference?!
you forget to initialize c Context instance with Activity Context before passing it to SimpleAdapter.so pass Activity Context to Adapter as:
ListAdapter adapter = new SimpleAdapter(MainActivity.this,
contactList, R.layout.list_item,
new String[]{TAG_REFRENCE},
new int[]{R.id.photoRef});
MainActivity.this.setListAdapter(adapter);
and onPostExecute method already run on UI Thread then no need to use runOnUiThread for updating UI elements form onPostExecute
Related
when i enter data into search editbox and click data it gives the json data and first time gives result but second time i clicked the search editbox it shows the AsyncTask error..plz help to out this..thanks in advance
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.ListView;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.HashMap;
public class MainActivity extends AppCompatActivity {
JSONObject jsonobject;
ListView listview;
ListViewAdapter adapter;
EditText search;
ArrayList<HashMap<String, String>> arraylist;
static String name = "name";
static String temp = "temp";
static String pressure = "pressure";
DownloadJSON Asynctask= new DownloadJSON();
CityJson cityJson=new CityJson();
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
search= (EditText) findViewById(R.id.search);
search.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v)
{
String zipcode = search.getText().toString();
final String []params=
{"http://api.openweathermap.org/data/2.5/weather?q="+zipcode+",in&appid=2de143494c0b295cca9337e1e96b00e0"};
cityJson.execute(params);
}
});
Asynctask.execute();
}
private class CityJson extends AsyncTask<String,Void,Void>
{
#Override
protected Void doInBackground(String... params)
{
try
{
arraylist = new ArrayList<HashMap<String, String>>();
jsonobject = CityAsyncTask
.getJSONfromURL(params[0]);
HashMap<String, String> map = new HashMap<String, String>();
map.put("name", jsonobject.getString("name"));
JSONObject mainobJsonObject = jsonobject.getJSONObject("main");
map.put("temp", mainobJsonObject.getString("temp"));
map.put("pressure", mainobJsonObject.getString("pressure"));
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) findViewById(R.id.listview);
// Pass the results into ListViewAdapter.java
adapter = new ListViewAdapter(MainActivity.this, arraylist);
// Set the adapter to the ListView
listview.setAdapter(adapter);
// Close the progressdialog
}
}
private class DownloadJSON extends AsyncTask<Void, Void, Void>
{
#Override
protected Void doInBackground(Void...params) {
arraylist = new ArrayList<HashMap<String, String>>();
// Retrieve JSON Objects from the given URL address
try {
String [] weatherurl={"http://api.openweathermap.org/data/2.5/weather?zip=560086,in&appid=2de143494c0b295cca9337e1e96b00e0",
"http://api.openweathermap.org/data/2.5/weather?q=chennai,in&appid=2de143494c0b295cca9337e1e96b00e0",
"http://api.openweathermap.org/data/2.5/weather?q=delhi,in&appid=2de143494c0b295cca9337e1e96b00e0",
"http://api.openweathermap.org/data/2.5/weather?q=mumbai,in&appid=2de143494c0b295cca9337e1e96b00e0",
"http://api.openweathermap.org/data/2.5/weather?q=kolkata,in&appid=2de143494c0b295cca9337e1e96b00e0"};
for (int i = 0; i < weatherurl.length; i++) {
jsonobject = CityAsyncTask
.getJSONfromURL(weatherurl[i]);
HashMap<String, String> map = new HashMap<String, String>();
map.put("name", jsonobject.getString("name"));
JSONObject mainobJsonObject = jsonobject.getJSONObject("main");
map.put("temp", mainobJsonObject.getString("temp"));
map.put("pressure", mainobJsonObject.getString("pressure"));
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) findViewById(R.id.listview);
// Pass the results into ListViewAdapter.java
adapter = new ListViewAdapter(MainActivity.this, arraylist);
// Set the adapter to the ListView
listview.setAdapter(adapter);
// Close the progressdialog
}
}
}
You can execute a Particular asynctask only once. You need to create a new asynctask instance to execute again.
Read Threading rules in AsyncTask|Android Developers for more info.
search.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v)
{
String zipcode = search.getText().toString();
final String []params=
{"http://api.openweathermap.org/data/2.5/weather?q="+zipcode+",in&appid=2de143494c0b295cca9337e1e96b00e0"};
//cityJson.execute(params);
//Replace above line with following line
cityJson = new CityJson();
cityJson.execute(params);
}
});
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();
}
This question already has answers here:
fragment.onCreateView causes null pointer exception
(3 answers)
Closed 7 years ago.
I get a NullPointerException at Fragement's OnCreateView() methods. I've tried several things, but the error keeps showing up. I think the error comes from the listview.
This is my code:
package com.imptmd.charliemacdonald.desleutelaar;
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.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ListAdapter;
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;
public class SlotenFragment extends ListFragment {
private ProgressDialog nDialog;
// URL to get contacts JSON
private static String url = "http://charlenemacdonald.com/sloten.json";
// JSON Node names
private static final String TAG_SLOTEN = "slotenlijst";
private static final String TAG_SLOT = "Slot";
// contacts JSONArray
JSONArray sloten= null;
// Hashmap for ListView
ArrayList<HashMap<String, String>> slotenLijst;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
final View rootView = inflater.inflate(R.layout.fragment_sloten, container, false);
slotenLijst = new ArrayList<HashMap<String, String>>();
ListView lv = (ListView) getView().findViewById(android.R.id.list);
// 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 Slot = ((TextView) rootView.findViewById(R.id.textviewslotnaam))
.getText().toString();
// Starting single contact activity
Intent in = new Intent(getActivity().getApplicationContext(),
SlotInfoScherm1.class);
in.putExtra(TAG_SLOT, Slot);
startActivity(in);
}
});
return rootView;
// Calling async task to get json
}
/**
* Async task class to get json by making HTTP call
* */
private class GetSloten extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
// Showing progress dialog
nDialog = new ProgressDialog(getActivity());
nDialog.setMessage("Even geduld a.u.b., studenten worden geladen...");
nDialog.setCancelable(false);
nDialog.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
sloten = jsonObj.getJSONArray(TAG_SLOTEN);
// looping through All Contacts
for (int i = 0; i < sloten.length(); i++) {
JSONObject c = sloten.getJSONObject(i);
String Slot = c.getString(TAG_SLOT);
// tmp hashmap for single contact
HashMap<String, String> sloten = new HashMap<String, String>();
// adding each child node to HashMap key => value
sloten.put(TAG_SLOT, Slot);
// adding contact to contact list
slotenLijst.add(sloten);
}
} 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 (nDialog.isShowing())
nDialog.dismiss();
/**
* Updating parsed JSON data into ListView
* */
ListAdapter adapter = new SimpleAdapter(getActivity(), slotenLijst,
R.layout.sloten_info, new String[] { TAG_SLOT}, new int[] { R.id.textviewslotnaam});
setListAdapter(adapter);
}
}
}
Thanks in advance!
In your onCreateView() method, replace
ListView lv = (ListView) getView().findViewById(android.R.id.list);
with
ListView lv = (ListView) rootView.findViewById(android.R.id.list);
The getView() method cannot be called before onCreateView() returns, as getView() in effect returns the View created by onCreateView().
Call findViewById() on the rootView you just inflated, not on the activity.
The view hierarchy you just inflated is not yet a part of the activity view hierarchy.
Hello I am using the tutorial from androidhive for working with MySQL and so on.
I want to use the following activity as a fragment - but I have to transfer the ListActivity into ListFragment - when I just change the extend from ListActivity to ListFragment different error appear
AllProductsActivity.java
package com.example.androidhive;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import org.apache.http.NameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.ListActivity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;
public class AllProductsActivity extends ListActivity {
// Progress Dialog
private ProgressDialog pDialog;
// Creating JSON Parser object
JSONParser jParser = new JSONParser();
ArrayList<HashMap<String, String>> productsList;
// url to get all products list
private static String url_all_products = "http://api.androidhive.info/android_connect/get_all_products.php";
// JSON Node names
private static final String TAG_SUCCESS = "success";
private static final String TAG_PRODUCTS = "products";
private static final String TAG_PID = "pid";
private static final String TAG_NAME = "name";
// products JSONArray
JSONArray products = null;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.all_products);
// Hashmap for ListView
productsList = new ArrayList<HashMap<String, String>>();
// Loading products in Background Thread
new LoadAllProducts().execute();
// Get listview
ListView lv = getListView();
// on seleting single product
// launching Edit Product Screen
lv.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// getting values from selected ListItem
String pid = ((TextView) view.findViewById(R.id.pid)).getText()
.toString();
// Starting new intent
Intent in = new Intent(getApplicationContext(),
EditProductActivity.class);
// sending pid to next activity
in.putExtra(TAG_PID, pid);
// starting new activity and expecting some response back
startActivityForResult(in, 100);
}
});
}
// Response from Edit Product Activity
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
// if result code 100
if (resultCode == 100) {
// if result code 100 is received
// means user edited/deleted product
// reload this screen again
Intent intent = getIntent();
finish();
startActivity(intent);
}
}
/**
* Background Async Task to Load all product by making HTTP Request
* */
class LoadAllProducts extends AsyncTask<String, String, String> {
/**
* Before starting background thread Show Progress Dialog
* */
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(AllProductsActivity.this);
pDialog.setMessage("Loading products. Please wait...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(false);
pDialog.show();
}
/**
* getting All products from url
* */
protected String doInBackground(String... args) {
// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
// getting JSON string from URL
JSONObject json = jParser.makeHttpRequest(url_all_products, "GET", params);
// Check your log cat for JSON reponse
Log.d("All Products: ", json.toString());
try {
// Checking for SUCCESS TAG
int success = json.getInt(TAG_SUCCESS);
if (success == 1) {
// products found
// Getting Array of Products
products = json.getJSONArray(TAG_PRODUCTS);
// looping through All Products
for (int i = 0; i < products.length(); i++) {
JSONObject c = products.getJSONObject(i);
// Storing each json item in variable
String id = c.getString(TAG_PID);
String name = c.getString(TAG_NAME);
// creating new HashMap
HashMap<String, String> map = new HashMap<String, String>();
// adding each child node to HashMap key => value
map.put(TAG_PID, id);
map.put(TAG_NAME, name);
// adding HashList to ArrayList
productsList.add(map);
}
} else {
// no products found
// Launch Add New product Activity
Intent i = new Intent(getApplicationContext(),
NewProductActivity.class);
// Closing all previous activities
i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(i);
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
/**
* After completing background task Dismiss the progress dialog
* **/
protected void onPostExecute(String file_url) {
// dismiss the dialog after getting all products
pDialog.dismiss();
// updating UI from Background Thread
runOnUiThread(new Runnable() {
public void run() {
/**
* Updating parsed JSON data into ListView
* */
ListAdapter adapter = new SimpleAdapter(
AllProductsActivity.this, productsList,
R.layout.list_item, new String[] { TAG_PID,
TAG_NAME},
new int[] { R.id.pid, R.id.name });
// updating listview
setListAdapter(adapter);
}
});
}
}
}
What I have to change, so I can use that as a fragment?
Edit:
i tried to change the code a little bit following some tutorials on the web...
now it works better, but there is still some problems with onPostExecute...
the doInBackground gets all parameters from mysql. i can track that with debug, but somehow after doInBackground it get's there is an error..
package com.example.androidhive;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import org.apache.http.NameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.ListActivity;
import android.app.ProgressDialog;
import android.content.Intent;
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.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;
public class AllProductsActivity extends ListFragment {
// Progress Dialog
private ProgressDialog pDialog;
// Creating JSON Parser object
JSONParser jParser = new JSONParser();
ArrayList<HashMap<String, String>> productsList;
// url to get all products list
private static String url_all_products = "http://10.0.2.2/android_connect/get_all_products.php";
// JSON Node names
private static final String TAG_SUCCESS = "success";
private static final String TAG_PRODUCTS = "products";
private static final String TAG_PID = "pid";
private static final String TAG_NAME = "name";
// products JSONArray
JSONArray products = null;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// TODO Auto-generated method stub
// Hashmap for ListView
// Hashmap for ListView
productsList = new ArrayList<HashMap<String, String>>();
// Loading products in Background Thread
new LoadAllProducts().execute();
return inflater.inflate(R.layout.all_products, container, false);
}
/**
* 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(getActivity());
pDialog.setMessage("Loading products. Please wait...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(false);
pDialog.show();
}
/**
* getting All products from url
* */
protected String doInBackground(String... args) {
// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
// getting JSON string from URL
JSONObject json = jParser.makeHttpRequest(url_all_products, "GET", params);
// Check your log cat for JSON reponse
Log.d("All Products: ", json.toString());
try {
// Checking for SUCCESS TAG
int success = json.getInt(TAG_SUCCESS);
if (success == 1) {
// products found
// Getting Array of Products
products = json.getJSONArray(TAG_PRODUCTS);
// looping through All Products
for (int i = 0; i < products.length(); i++) {
JSONObject c = products.getJSONObject(i);
// Storing each json item in variable
String id = c.getString(TAG_PID);
String name = c.getString(TAG_NAME);
// creating new HashMap
HashMap<String, String> map = new HashMap<String, String>();
// adding each child node to HashMap key => value
map.put(TAG_PID, id);
map.put(TAG_NAME, name);
// adding HashList to ArrayList
productsList.add(map);
}
}
} 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
getActivity().runOnUiThread(new Runnable() {
public void run() {
/**
* Updating parsed JSON data into ListView
* */
ListAdapter adapter = new SimpleAdapter(
getActivity(), productsList,
R.layout.list_item, new String[] { TAG_PID,
TAG_NAME},
new int[] { R.id.pid, R.id.name });
// updating listview
setListAdapter(adapter);
}
});
}
}
}
You must create fragment in FragmentActivity. All code you need is below
MainActivity.java
public class MainActivity extends FragmentActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.fragment_activity);
int index=0;
MyListFragment f = MyListFragment.newInstance(index);
FragmentTransaction ft = getSupportFragmentManager()
.beginTransaction();
ft.replace(R.id.mylist, f);
ft.commit();
}//end oncreate
}//end activity
Layout fragment_activity.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:baselineAligned="false"
android:layout_height="match_parent"
android:orientation="horizontal" >
<FrameLayout
android:id="#+id/mylist"
android:layout_weight="1"
android:layout_width="0px"
android:layout_height="match_parent" />
</LinearLayout>
MyListFragment.java
public class MyListFragment extends ListFragment {
public static MyListFragment newInstance(int index) {
MyListFragment f = new MyListFragment();
return f;
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.layout_mylist, container, false);
//read products from web and list
//productsList = new ArrayList<HashMap<String, String>>();
//new LoadProducts().execute();
return v;
}
//end oncreateview
class LoadProducts extends AsyncTask<String, String, String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
}
protected String doInBackground(String... args) {
return null;
}
protected void onPostExecute(String file_url) {
}
}
//end LoadProducts
}
layout_mylist.xml
<?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="wrap_content"
android:orientation="vertical" >
<TextView
android:id="#+id/details"
android:text="some text"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#drawable/white"
android:textColor="#drawable/black"
android:textStyle="bold"
android:paddingTop="6dip"
android:paddingLeft="6dip"
android:textAppearance="?android:attr/textAppearanceMedium" />
<ListView
android:id="#android:id/list"
android:layout_width="fill_parent"
android:layout_height="wrap_content"/>
</LinearLayout>
I'm tyring to get data from my website and then put that info into a spinner. I've used some tutorials and i came up with this code
package com.thenewboston.christian;
import java.util.ArrayList;
import java.util.List;
import org.apache.http.NameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.Activity;
import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.widget.ArrayAdapter;
import android.widget.Spinner;
public class hospitalhttp extends Activity{
private ProgressDialog pDialog;
JSONParser jParser = new JSONParser();
private static String url_all_products = "http://www.photosbychristian.com/ems/hospitals.php";
//private static final String TAG_HID = "hid";
private static final String TAG_HOSPITAL = "hospital";
JSONArray hosps = null;
ArrayAdapter <String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item );
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.spinnertest);
new LoadAllProducts().execute();
}
class LoadAllProducts extends AsyncTask<String, String, String> {
/**
* Before starting background thread Show Progress Dialog
* */
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(hospitalhttp.this);
pDialog.setMessage("Loading hospitals. Please wait...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(false);
pDialog.show();
}
/**
* getting All products from url
* */
protected String doInBackground(String... args) {
// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
// getting JSON string from URL
JSONObject json = jParser.makeHttpRequest(url_all_products, "GET",
params);
// Check your log cat for JSON reponse
Log.d("All Products: ", json.toString());
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
try {
// products found
// Getting Array of Products
hosps = json.getJSONArray("PA");
// looping through All Products
for (int i = 0; i < hosps.length(); i++) {
JSONObject c = hosps.getJSONObject(i);
// Storing each json item in variable
//String id = c.getString(TAG_HID);
String name = c.getString(TAG_HOSPITAL);
adapter.add(name);
}
} 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
*/
Spinner state = (Spinner) findViewById(R.id.spinner1);
state.setAdapter(adapter);
}
});
}
}
}
I try and run my app and i get this error
02-22 22:29:48.131: E/AndroidRuntime(1200): java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{com.thenewboston.christian/com.thenewboston.christian.hospitalhttp}: java.lang.IllegalStateException: System services not available to Activities before onCreate()
So i move all of this after the oncreate bolck and i still get the same error
private ProgressDialog pDialog;
JSONParser jParser = new JSONParser();
private static String url_all_products = "http://www.photosbychristian.com/ems/hospitals.php";
//private static final String TAG_HID = "hid";
private static final String TAG_HOSPITAL = "hospital";
JSONArray hosps = null;
ArrayAdapter <String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item );
And so i have no idea what to do know any help would be greatly appreciated
Moving the code around is not going to help. Java is a scoped language, it doesn't matter if something is placed after or before a method. It is still in the same scope.
The issue is probably raised by this line:
ArrayAdapter <String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item );
You want to load a layout in an object scoped initializer. This kind of code runs even before the constructor. You must move the value assignment into the onCreate method like this:
ArrayAdapter <String> adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.spinnertest);
adapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item);
new LoadAllProducts().execute();
}
So i move all of this after the oncreate bolck and i still get the same error
That code cannot be inside a method, as you are declaring static values. Hence, that code must reside outside any method, which means that it will be executed before any method, and therefore will be executed before onCreate().
Something in there -- probably your JSONParser -- is trying to do something that cannot be done until after super.onCreate() has been executed in your onCreate() method. Your Java stack trace will tell you specifically which of these lines (if any) is the source of your difficulty. You then need to have that code be executed after super.onCreate() is called, such as by putting it at the end of your onCreate() method.