I have 2 simple working apps that I'm trying to combine. #1 plays a video in a videoview from a URL that I specified, and #2 loads information from a database. I'm just trying to put the videoview in the same area as the information loading from the database.
The videoview appears in the right place, but the app crashes when I add this code anywhere in onCreate:
// **NEW VIDEOVIEW CODE**
VideoView vid = (VideoView) findViewById(R.id.videoView);
Uri video = Uri.parse(MOVIE_URL);
vid.setMediaController(new MediaController(this));
vid.setVideoURI(video);
vid.start();
vid.requestFocus();
With trial and error I determined that it crashes starting at the 'setMediaController' line. Here is the onCreate(which works fine without the above code, other than the blank videoview obviously):
#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);
}
});
}
Here is the logcat:
05-10 15:33:29.064: I/Adreno-EGL(7866): <qeglDrvAPI_eglInitialize:320>: EGL 1.4 QUALCOMM Build: I0404c4692afb8623f95c43aeb6d5e13ed4b30ddbDate: 11/06/13
05-10 15:33:29.084: D/OpenGLRenderer(7866): Enabling debug mode 0
05-10 15:33:30.214: D/AndroidRuntime(7866): Shutting down VM
05-10 15:33:30.214: W/dalvikvm(7866): threadid=1: thread exiting with uncaught exception (group=0x41898ba8)
05-10 15:33:30.214: E/AndroidRuntime(7866): FATAL EXCEPTION: main
05-10 15:33:30.214: E/AndroidRuntime(7866): Process: com.example.androidhive, PID: 7866
05-10 15:33:30.214: E/AndroidRuntime(7866): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.androidhive/com.example.androidhive.AllProductsActivity}: java.lang.NullPointerException
05-10 15:33:30.214: E/AndroidRuntime(7866): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2195)
In summary, I'm trying to figure out if I'm going about these entirely wrong or if there is a way to include this code without crashing. Thanks!!
EDIT I apologize for not posting these earlier, I just didn't want to overwhelm people.
Here is my list_item.xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="vertical" >
<!-- Product id (pid) - will be HIDDEN - used to pass to other activity -->
<TextView
android:id="#+id/pid"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:visibility="gone" />
<!-- Name Label -->
<TextView
android:id="#+id/name"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:paddingTop="6dip"
android:paddingLeft="6dip"
android:textSize="17dip"
android:textStyle="bold" />
<TextView
android:id="#+id/description"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:paddingTop="6dip"
android:paddingLeft="6dip"
android:textSize="17dip"
android:textStyle="bold" />
<VideoView
android:id="#+id/videoView"
android:layout_width="100dp"
android:layout_height="100dp"
/>
</LinearLayout>
Here is my all_products.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical">
<!-- Main ListView
Always give id value as list(#android:id/list)
-->
<ListView
android:id="#android:id/list"
android:layout_width="fill_parent"
android:layout_height="wrap_content"/>
</LinearLayout>
And finally... here is my ENTIRE AllProductsActivity.java file:
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.net.Uri;
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.MediaController;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import android.widget.VideoView;
public class AllProductsActivity extends ListActivity {
// Progress Dialog
private ProgressDialog pDialog;
// Creating JSON Parser object
JSONParser jParser = new JSONParser();
ArrayList<HashMap<String, String>> productsList;
// get video url
private static final String MOVIE_URL ="http://mywebsite.com/mycameraapp/android_connect/videos/testvideo.mkv";
// url to get all products list
private static String url_all_products = "http://mywebsite.com/mycameraapp/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";
private static final String TAG_DESCRIPTION = "description";
// 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();
// **NEW VIDEOVIEW CODE**
VideoView vid = (VideoView) findViewById(R.id.videoView);
Uri video = Uri.parse(MOVIE_URL);
vid.setMediaController(new MediaController(this));
vid.setVideoURI(video);
vid.start();
vid.requestFocus();
// 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);
String description = c.getString(TAG_DESCRIPTION);
// 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_DESCRIPTION, description);
// 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, TAG_DESCRIPTION},
new int[] { R.id.pid, R.id.name, R.id.description });
// updating listview
setListAdapter(adapter);
}
});
}
}
}
You are receiving the error because the VideoView element is not available in the all_products.xml file.
What you need to do is create a ListAdapter and have the getView() method of the list adapter reference your list_item.xml layout file. That is the file that contains the VideoView.
Related
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 am working on an android application. I am able to display values from the database into the listview but i want to display them into the spinner instead of listview. Here is the code which i have written for listview
package com.example.festipedia_logo;
//import com.actionbarsherlock.app.SherlockFragment;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import com.actionbarsherlock.app.SherlockFragmentActivity;
import com.example.festipedia_logo.details2.LoadAllProducts;
import android.app.Activity;
import android.app.Fragment;
import android.app.ProgressDialog;
import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.view.ViewPager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
public class mainpageact extends SherlockFragmentActivity {
Button button1;
Button button4;
ArrayAdapter<String> adapter1;
// String[] city;
String loc;
Spinner spinner;
String location;
ArrayAdapter<String> adapter;
String[] city;
// Progress Dialog
private ProgressDialog pDialog;
String az;
// Creating JSON Parser object
JSONParser jParser = new JSONParser();
EditText b;
// ArrayList<HashMap<String, String>> productsList;
ArrayList<String> productsList;
// url to get all products list
private static String url_all_products = "http://192.168.0.104:8080/festipedia/sports.php";
Button a;
// JSON Node names
private static final String TAG_SUCCESS = "success";
private static final String TAG_PRODUCTS = "products";
private static final String TAG_NAME = "eventname";
// products JSONArray
JSONArray products = null;
ListView l;
// Spinner spinner;
//String loc;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//setContentView(R.layout.activity_main);
getActionBar().setDisplayShowTitleEnabled(false);
getActionBar().setDisplayUseLogoEnabled(false);
getActionBar().setDisplayShowCustomEnabled(true);
getActionBar().setDisplayShowHomeEnabled(false);
//getSupportActionBar().setIcon(R.drawable.fest);
//getSupportActionBar().setLogo(R.drawable.fest);
Drawable d=getResources().getDrawable(R.drawable.a5);
getActionBar().setBackgroundDrawable(d);
setContentView(R.layout.mainmenu);
spinner = (Spinner)this.findViewById(R.id.spinner1);
spinner.setAdapter(adapter);
productsList = new ArrayList<String>();
// productsList = new ArrayList<HashMap<String, String>>();
new LoadAllProducts().execute();
spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
location=spinner.getSelectedItem().toString();
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}});
// View rootView = inflater.inflate(R.layout.mainmenu, container, false);
//Intent in = getIntent();
//loc = in.getStringExtra("loc");
Button button1 = (Button) findViewById(R.id.button1);
Button button4 = (Button) findViewById(R.id.button4);
Button button2 = (Button) findViewById(R.id.button2);
Button button5 = (Button) findViewById(R.id.button5);
Button button3 = (Button) findViewById(R.id.button3);
//TextView t1= (TextView) findViewById(R.id.getlocation);
//t1.setText(loc);
button1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
// creating new product in background thread
/*final FragmentTransaction ft = getFragmentManager().beginTransaction();
ft.replace(R.id.content_frame,new home1() , "Fest Content");
ft.commit();*/
Intent i = new Intent(getApplicationContext(),
MainActivity.class);
// Closing all previous activities
//i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(i);
//new CreateNewProduct().execute();
}
});
button4.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
// creating new product in background thread
/* final FragmentTransaction ft = getFragmentManager().beginTransaction();
ft.replace(R.id.content_frame,new testing() , "Fest Content");
ft.commit();*/
Intent i = new Intent(getApplicationContext(),
testing.class);
// Closing all previous activities
//i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(i);
//new CreateNewProduct().execute();
}
});
button5.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
// creating new product in background thread
/* final FragmentTransaction ft = getFragmentManager().beginTransaction();
ft.replace(R.id.content_frame,new testing() , "Fest Content");
ft.commit();*/
Intent i = new Intent(getApplicationContext(),
search.class);
startActivity(i);
}
});
button2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
// creating new product in background thread
/*final FragmentTransaction ft = getFragmentManager().beginTransaction();
ft.replace(R.id.content_frame,new home1() , "Fest Content");
ft.commit();*/
Intent i = new Intent(getApplicationContext(),
MainActivity.class);
// Closing all previous activities
//i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(i);
//new CreateNewProduct().execute();
}
});
button3.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
// creating new product in background thread
/*final FragmentTransaction ft = getFragmentManager().beginTransaction();
ft.replace(R.id.content_frame,new home1() , "Fest Content");
ft.commit();*/
Intent i = new Intent(getApplicationContext(),
CopyMainActivity.class);
// Closing all previous activities
//i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
i.putExtra("location", location);
// starting new activity and expecting some response back
startActivityForResult(i, 100);
//startActivity(i);
//new CreateNewProduct().execute();
}
});
}
class LoadAllProducts extends AsyncTask<String, String, String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(mainpageact.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>();
params.add(new BasicNameValuePair("location", az));
// getting JSON string from URL
JSONObject json = jParser.makeHttpRequest(url_all_products, "GET", params);
// 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 name = c.getString(TAG_NAME);
// city[i] = name;
String name = c.getString(TAG_NAME);
productsList.add(name);
//l.setFilterText(id);
// creating new HashMap
// HashMap<String, String> map = new HashMap<String, String>();
// adding each child node to HashMap key => value
// map.put(TAG_NAME, name);
// adding HashList to ArrayList
// productsList.add(map);
}
} else {
// no products found
// Launch Add New product Activity
}
} 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
* */
// city = new String[] { "Mumbai", "Chennai",
// "Dubai"};
// adapter = new ArrayAdapter<String>(mainpageact.this, R.layout.list_item, productsList);
//ArrayAdapter<CharSequence>
adapter = new ArrayAdapter<String>(mainpageact.this,R.layout.mainmenu, productsList);
spinner.setAdapter(adapter);
adapter.notifyDataSetChanged();
//spinner.setAdapter(adapter);
}
});
}
}
}
It seems, that you are not calling notifyDataSetChanged() after you have loaded the Spinner on onPostExecute(). That will tell your adapter that the data of the spinner needs to be refreshed.
So, basically try this:
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
* */
// city = new String[] { "Mumbai", "Chennai",
// "Dubai"};
adapter = new ArrayAdapter<String>(mainpageact.this, productsList,
R.layout.list_item, new String[] {
TAG_NAME},
new int[] { R.id.name });
adapter.notifyDataSetChanged();
}
});
}
NOTE: When you set the spinner to the adapter on your OnCreate(), the adapter is null at that moment. Try doing it inside the onPostExecute(). Also, try to avoid the use of that Thread inside the AsyncTask. It seems unnecessary, but I might be wrong.
There are three issue in your code.
1) Change the productsList declaration as ArrayList( I don't see any need of having HashMap)
So change this line
ArrayList<HashMap<String, String>> productsList;
to
ArrayList<String> productsList;
and instantiate the productsList as
productsList = new ArrayList<String>();
2) In doInBackground() add the response string item directly to the productsList.
String name = c.getString(TAG_NAME);
productsList.add(name);
3) Now the main issue , change the adapter as
adapter = new ArrayAdapter<String>(this,R.layout.list_item, productsList);
spinner.setAdapter(adapter);
I am developing and android app that retrieves news from mysql database and populate them in list view, i managed to retrieve data successfully but am facing one major problem that stops me from proceeding with my project. When i try to populate data in listview the app crashes in displaying the following error in log cat saying
your content must have a ListView whose id attribute is 'android.R.id.list'
I have tried to change my xml listview id and write it in different forms but it still fails and displaying same error.
here are my xml codes.
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<ListView
android:id="#+id/android.R.id.list"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:background="#fff" />
<LinearLayout
android:id="#+id/read_news"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:weightSum="2"
android:baselineAligned="false" />
</LinearLayout>
here are my java codes
package com.jetas.sportsapp;
import java.util.ArrayList;
import java.util.HashMap;
import org.json.JSONArray;
import org.json.JSONObject;
import android.annotation.SuppressLint;
import android.app.ListActivity;
import android.os.Bundle;
import android.os.StrictMode;
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;
import com.jetas.sportsapp.utils.JsonUtils;
public class News extends ListActivity {
// private ProgressDialog pDialog;
private ArrayList<HashMap<String,String>> mCommentList;
#SuppressLint("NewApi")
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.news_single_post);
StrictMode.enableDefaults();
ArrayList<HashMap<String,String>> newsList = getData();
updateList(newsList);
}
public ArrayList<HashMap<String,String>> getData() {
TextView textview = (TextView) findViewById(R.id.newsTitle);
try {
// String s = "";
String news =
JsonUtils.read("http://10.0.2.2/index.php/android/news?offset=0&limit=10");
Log.d("News data",news);
JSONArray jArray = new JSONArray(news);
Log.d("Parsing json", jArray.toString());
for (int i = 0; i < jArray.length(); i++) {
JSONObject json = jArray.getJSONObject(i);
String title = json.getString("title");
String content = json.getString("content");
// creating new HashMap
HashMap<String, String> map = new HashMap<String, String>();
map.put("title", title);
map.put("content", content);
// adding HashList to ArrayList
mCommentList.add(map);
// textview.setText(title);
// s = s + "Title: " + json.getString("title") + "\n"
// + "Content: " + json.getString("content") +
"\n\n";
// textview.setText(s);
}
} catch (Exception e) {
Log.e("log_tag", "Error Parsing Data" + e.toString());
textview.setText("Error in Parsing Data !!!!!");
}
return mCommentList;
}
/**
* Inserts the parsed data into the listview.
*/
private void updateList(ArrayList<HashMap<String,String>> newsLists) {
// 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, newsLists,
R.layout.news_single_post, new String[] { "title",
"content"}, new int[] { R.id.newsTitle, R.id.content,});
// 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...
ListView lv = getListView();
lv.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// This method is triggered if an item is click
// within our
// list. For our example we won't be using this, but
// it is useful to know in real life applications.
}
});
}
// public class LoadComments extends AsyncTask<Void, Void, Boolean> {
//
// #Override
// protected void onPreExecute() {
// super.onPreExecute();
// pDialog = new ProgressDialog(News.this);
// pDialog.setMessage("Loading Comments...");
// pDialog.setIndeterminate(false);
// pDialog.setCancelable(true);
// pDialog.show();
// }
// #Override
// protected Boolean doInBackground(Void... arg0) {
// //we will develop this method in version 2
// getData();
// return null;
//
// }
//
//
// #Override
// protected void onPostExecute(Boolean result) {
// super.onPostExecute(result);
// pDialog.dismiss();
// //we will develop this method in version 2
// updateList();
// }
}
I also want to set such that when user clicks on the news the new activity opens with the details of the news.
Try this..
Change this android:id="#+id/android.R.id.list" to android:id="#android:id/list" like below
<ListView
android:id="#android:id/list"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:background="#fff" />
I have faced same problem and solved by following
Listview lv;
lv = (listview) Findviewbyid(android.R.id.listviewname);
I'm using class that extends AsyncTask but I have error at the line that executes the class
I couldn't figure it out
here is the class that includes my main class and the class that extends AsyncTask
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 com.example.androidhive.library.JSONParser;
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 void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.topics_list);
// Hashmap for ListView
TopicsList = new ArrayList<HashMap<String, String>>();
**// Loading products in Background Thread
new LoadAllTopics().execute();**
// Get listview
ListView lv = getListView();
// on seleting single product
// launching Edit Product Screen
lv.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
// getting values from selected ListItem
String tid = ((TextView) view.findViewById(R.id.tid)).getText()
.toString();
/**
* Background Async Task to Load all product by making HTTP Request
* */
class LoadAllTopics extends AsyncTask<String, String, String> {
/**
* Before starting background thread Show Progress Dialog
* */
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(Topics_list.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_topics, "GET", params);
// Check your log cat for JSON reponse
Log.d("All topics: ", json.toString());
try {
// Checking for SUCCESS TAG
int success = json.getInt(TAG_SUCCESS);
if (success == 1) {
// products found
// Getting Array of Products
topics = json.getJSONArray(TAG_TOPICS);
// looping through All Products
for (int i = 0; i < topics.length(); i++) {
JSONObject c = topics.getJSONObject(i);
// Storing each json item in variable
String id = c.getString(TAG_TOPICSID);
String topict = c.getString(TAG_TOPICTITLE);
String username = c.getString(TAG_TOPICAUTHOR);
// creating new HashMap
HashMap<String, String> map = new HashMap<String, String>();
// adding each child node to HashMap key => value
map.put(TAG_TOPICSID, id);
map.put(TAG_TOPICTITLE, topict);
map.put(TAG_TOPICAUTHOR, username);
// adding HashList to ArrayList
TopicsList.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(
Topics_list.this, TopicsList,
R.layout.list_item, new String[] { TAG_TOPICSID,TAG_TOPICTITLE,
TAG_TOPICAUTHOR},
new int[] { R.id.tid, R.id.name });
// updating listview
setListAdapter(adapter);
}
});
}
}
} });}}
the error is at the bold line
really appreciate your help
In Java you need to write the method inside the class. Put the onCreate inside Class.
public class MainActivity extends Activity {
public void onCreate(Bundle savedInstanceState) {
.....
lv.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
// getting values from selected ListItem
String tid = ((TextView) view.findViewById(R.id.tid)).getText()
.toString();
}
});
.........
}
private class LoadAllTopics extends AsyncTask<String, String, String> {
.....
}
}