Fragment not being replaced, be placed on top of other fragment - android

I am slowly converting my app to fragments vs activities, and I am getting some odd behavior at the moment. I have a button that when pressed should load a new fragment into view then execute an async task in order to load information into the fragment.
My code for the fragment which contains the button to swap the new fragment is:
public class Discover extends Fragment {
Fragment Fragment_one;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.activity_discover, container, false);
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(getActivity());
String userName = prefs.getString("userName", null);
String userID = prefs.getString("userID", null);
//add button onclick programatically
Button bt = (Button)v.findViewById(R.id.discoverBeers);
bt.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// do whatever stuff you wanna do here
FragmentManager man=getFragmentManager();
FragmentTransaction tran=man.beginTransaction();
Fragment_one=new BPTopBeers();
tran.add(R.id.main, Fragment_one);//tran.
tran.addToBackStack(null);
tran.commit();
}
});
// Inflate the layout for this fragment
//todo: change to discover layout
return v;
}
I know it loading on top of the other fragment and not swapping because I can see the other fragment below it:
The fragment that is loaded on the button click is:
public class BPTopBeers extends Fragment {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.toptaste_layout, container, false);
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(getActivity());
String userName = prefs.getString("userName", null);
String userID = prefs.getString("userID", null);
String title = "Top Beers on Beer Portfolio";
TextView topTitle = (TextView) v.findViewById(R.id.topTasteTitle);
topTitle.setText(title);
//construct url
String url = "myURL";
Log.d("myUrl", url);
//async task goes here
new GetYourTopTasteBeers(getActivity()).execute(url);
// Inflate the layout for this fragment
return v;
}
and the async task which is called in that fragment looks like this:
public class GetYourTopTasteBeers extends AsyncTask<String, Void, String> {
Context c;
private ProgressDialog Dialog;
public GetYourTopTasteBeers (Context context)
{
c = context;
Dialog = new ProgressDialog(c);
}
#Override
protected String doInBackground(String... arg0) {
// TODO Auto-generated method stub
return readJSONFeed(arg0[0]);
}
protected void onPreExecute() {
Dialog.setMessage("Getting beers");
Dialog.setTitle("Loading");
Dialog.setCancelable(false);
Dialog.show();
}
protected void onPostExecute(String result){
//decode json here
try{
JSONArray jsonArray = new JSONArray(result);
//acces listview
ListView lv = (ListView) ((Activity) c).findViewById(R.id.topTasteBeers);
//make array list for beer
final List<ShortBeerInfo> tasteList = new ArrayList<ShortBeerInfo>();
for(int i = 0; i < jsonArray.length(); i++) {
String beer = jsonArray.getJSONObject(i).getString("beer");
String rate = jsonArray.getJSONObject(i).getString("rate");
String beerID = jsonArray.getJSONObject(i).getString("id");
String breweryID = jsonArray.getJSONObject(i).getString("breweryID");
int count = i + 1;
beer = count + ". " + beer;
//create object
ShortBeerInfo tempTaste = new ShortBeerInfo(beer, rate, beerID , breweryID);
//add to arraylist
tasteList.add(tempTaste);
//add items to listview
ShortBeerInfoAdapter adapter1 = new ShortBeerInfoAdapter(c ,R.layout.brewer_stats_listview, tasteList);
lv.setAdapter(adapter1);
//set up clicks
lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1,
int arg2, long arg3) {
ShortBeerInfo o=(ShortBeerInfo)arg0.getItemAtPosition(arg2);
String tempID = o.id;
String tempBrewID = o.brewery;
Toast toast = Toast.makeText(c, tempID, Toast.LENGTH_SHORT);
toast.show();
//todo: change fragment to beer page
//Intent myIntent = new Intent(c, BeerPage2.class);
//myIntent.putExtra("id", tempID);
//myIntent.putExtra("breweryID", tempBrewID);
//c.startActivity(myIntent);
}
});
}
}
catch(Exception e){
}
Dialog.dismiss();
}
public String readJSONFeed(String URL) {
StringBuilder stringBuilder = new StringBuilder();
HttpClient httpClient = new DefaultHttpClient();
HttpGet httpGet = new HttpGet(URL);
try {
HttpResponse response = httpClient.execute(httpGet);
StatusLine statusLine = response.getStatusLine();
int statusCode = statusLine.getStatusCode();
if (statusCode == 200) {
HttpEntity entity = response.getEntity();
InputStream inputStream = entity.getContent();
BufferedReader reader = new BufferedReader(
new InputStreamReader(inputStream));
String line;
while ((line = reader.readLine()) != null) {
stringBuilder.append(line);
}
inputStream.close();
} else {
Log.d("JSON", "Failed to download file");
}
} catch (Exception e) {
Log.d("readJSONFeed", e.getLocalizedMessage());
}
return stringBuilder.toString();
}
}

When you use add it just straight add the fragment to the view however when you use replace it removes the current fragment then adds the new one which is what you are looking for since it appears your XML is not set to match_parent

You can hide old fragment,if you want to back to previous
fragmentManager
.beginTransaction()
.hide(previous fragment)
.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE)
.add(R.id.content_frame, newFragment,
ParserConstants.FRAGMENT_MAIN).addToBackStack(null)
.commitAllowingStateLoss();

Related

How to get values from listview android?

I am new in android.I am fetching data from mysql and showing it in listview.things are working fine but now i want to pass the value to intent when user click on listview(Row).I have implemented setOnItemClickListener.but the list view is dynamic so i am not getting how to get values and pass it to the intent.
Thanks in advance
public class AdminNotice extends Activity {
private String[] navMenuTitles;
private TypedArray navMenuIcons;
private EditText editTextName;
SharedPreferences sp;
private String jsonResult;
private ListView listView;
private Button b;
EditText etname, et;
TextView tv;
String myJSON;
private static final String TAG = "MainActivity.java";
private static final String TAG_NAME = "notice";
private static final String TAG_DATE = "ndate";
ProgressBar progressBar;
Date date;
JSONArray peoples = null;
ArrayList<HashMap<String, String>> personList;
ListView list;
public static final String USER_NAME = "USERNAME";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.noticelist);
progressBar = (ProgressBar) findViewById(R.id.progressbar);
//SharedPreferences myprefs= getSharedPreferences("user", MODE_WORLD_READABLE);
// String session_id= myprefs.getString("session_id", null);
//TextView textView = (TextView) findViewById(R.id.fname);
//textView.setText("Welcome "+session_id);
navMenuTitles = getResources().getStringArray(R.array.nav_drawer_items);
navMenuIcons = getResources().obtainTypedArray(R.array.nav_drawer_icons);
// load icons from
// strings.xml
list = (ListView) findViewById(R.id.listView);
personList = new ArrayList<HashMap<String,String>>();
getData();
}
//send messages stop
//get json data start
protected void showList(){
try {
JSONArray peoples = new JSONArray(myJSON);
for(int i=0;i<peoples.length();i++){
JSONObject c = peoples.getJSONObject(i);
String name=null, date=null;
/*if(c==null){
ProgressDialog progress = new ProgressDialog(this);
progress.setTitle("Loading");
progress.setMessage("Wait while loading...");
progress.show();
}*/
if(c.has("notice"))
if(c.has("ndate"))
progressBar.setVisibility(View.GONE);
name = c.getString("notice");
date = c.getString("ndate");
HashMap<String,String> persons = new HashMap<String,String>();
persons.put(TAG_NAME,name);
persons.put(TAG_DATE,date);
personList.add(persons);
}
ListAdapter adapter = new SimpleAdapter(
AdminNotice.this, personList, R.layout.list_item1,
new String[]{TAG_NAME,TAG_DATE},
new int[]{R.id.name, R.id.date}
);
list.setAdapter(adapter);
list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int position,
long id) {
/*ModelClass obj = getItem(position);
String name = obj.getName();*/
// Simple Toast to show the position Selected
Log.d("SELECT_POSITION", "Position For this List Item = " + position);
}
});
/* list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView parent, View view, int position, long id) {
Toast.makeText(getApplicationContext(), ((TextView) view).getText(), Toast.LENGTH_SHORT).show();
}
});*/
} catch (JSONException e) {
Log.i("tagconvertstr", "["+myJSON+"]");
}
}
public void getData(){
class GetDataJSON extends AsyncTask<String, Void, String>{
#Override
protected String doInBackground(String... params) {
SharedPreferences myprefs= getSharedPreferences("user", MODE_WORLD_READABLE);
String session_id= myprefs.getString("session_id", null);
InputStream inputStream = null;
String result = null;
try {
String postReceiverUrl = "http://notice.php";
// HttpClient
HttpClient httpClient = new DefaultHttpClient();
// post header
HttpPost httpPost = new HttpPost(postReceiverUrl);
// add your data
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
nameValuePairs.add(new BasicNameValuePair("username", session_id));
httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpClient.execute(httpPost);
HttpEntity resEntity = response.getEntity();
inputStream = resEntity.getContent();
// json is UTF-8 by default
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null)
{
sb.append(line + "\n");
}
result = sb.toString();
} catch (Exception e) {
Log.i("tagconvertstr", "["+result+"]");
System.out.println(e);
}
finally {
try{if(inputStream != null)inputStream.close();}catch(Exception squish){}
}
return result;
}
#Override
protected void onPostExecute(String result){
myJSON = result;
showList();
}
}
GetDataJSON g = new GetDataJSON();
g.execute();
}
//get json data stop
}
Inside your listview onItemClickListener
Intent intent=new Intent(currentyactivty.this,secondactiviy.class);
intent.putExtra("TAG_NAME", personList.get(position).get(TAG_NAME));
startActivity(intent);
To getdata in second activity at onCreate method
String data;
Intent in=getIntent();
if(in!=null && in.hasExtra("TAG_NAME")){
data=in.getStringArrayExtra("TAG_NAME");
}
you can set text from view
list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int position,
long id) {
Intent intent=new Intent(currentyactivty.this,secondactiviy.class);
intent.putExtra("NAME", personList.get(position).get(TAG_NAME));
startActivity(intent);
// Simple Toast to show the position Selected
Log.d("SELECT_POSITION", "Position For this List Item = " + position);
}
});
list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int position,
long id) {
/*ModelClass obj = getItem(position);
String name = obj.getName();*/
String personName = personList.get(position).get(TAG_NAME);
Intent i = new Intent(AdminNotice.this, YourNextActivity.class);
i.putExtra("person_name", personName);
startActivity(i);
// Simple Toast to show the position Selected
Log.d("SELECT_POSITION", "Position For this List Item = " + position);
}
});
you can use bundle to pass you're data from intent.
list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int position,
long id) {
ModelClass obj = getItem(position);
String name = obj.getName();
String date = obj.getDate();
Bundle bundle = new Bundle();
bundle.putString("name", name);
bundle.putString("date", date );
Intent in = new Intent(currentActivity.this,destinationActivity.class);
in.putExtras(b);
startActivity(in);
// Simple Toast to show the position Selected
Log.d("SELECT_POSITION", "Position For this List Item = " + position);
}
});
and you can get it in your other activity by doing.
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_second);
Intent in = getIntent();
Bundle b = in.getExtras();
String name = b.getString("name");
String date = b.getString("date);
}
with this approach you don't have to hit the database again to retrieve data and you're one query is saved.
similarly you can send just you're 'id' also if you want.
but if you just want to pass 'id' then #Nas method would be more sorted and easy.

How to delete a list item from listview in android eclipse by clicking a button

I need to delete a list item from listview on clicking a delete button in android eclipse. The list values are populated from mysql database(JSON), so on deleting, I need to delete the same from database also.
Here is my main Activity; I need to delete a listitem from a listview on clicking a delete button on each item in the listview:
public class MainActivity extends Activity implements AsyncResponse2 {
private ProgressDialog dialog;
ListView l1;
//for getting count
TextView count;
private static final String TAG_COUNT = "cnt";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE); //to hide title bar
setContentView(R.layout.activity_main);
l1=(ListView)findViewById(R.id.listView1);
/** Reference to the delete button of the layout main.xml */
Button btnDel = (Button) findViewById(R.id.deleteid);
initView();
//str for getting count
count=(TextView)findViewById(R.id.countid);
//to display count while loading(so outside buttonclick)
String key1 = "saasvaap123";
String signupid1 = "8";
String url2 = "http://gooffers.in/omowebservices/index.php/webservice/Public_User/saved_offers_list?";
//http://gooffers.in/omowebservices/index.php/webservice/Public_User/saved_offers_list?key=saasvaap123&signup_id=8
//put the below lines outside button onclick since we load the values into edittext when opening the app
CustomHttpClient2 task2 = new CustomHttpClient2();
task2.execute(url2,key1,signupid1);
task2.delegate = MainActivity.this;
//end
}
//str getting count
//str customhttp2
private class CustomHttpClient2 extends AsyncTask<String, String, String>{
public AsyncResponse2 delegate=null;
private String msg;
#Override
protected void onPostExecute(String result2) {
// TODO Auto-generated method stub
super.onPostExecute(result2);
delegate.processFinish2(result2);
}
#Override
protected void onPreExecute() {
// TODO Auto-generated method stub
super.onPreExecute();
}
#Override
protected String doInBackground(String... params) {
if(params == null) return null;
// get url from params
String url2 = params[0];
String key1 = params[1];
String signupid1 = params[2];
ArrayList<NameValuePair> postParameters;
postParameters = new ArrayList<NameValuePair>();
postParameters.add(new BasicNameValuePair("key",key1));
postParameters.add(new BasicNameValuePair("signup_id",signupid1));
try {
// create http connection
HttpClient client = new DefaultHttpClient();
HttpPost httppost = new HttpPost(url2);
httppost.setEntity(new UrlEncodedFormEntity(postParameters));
// connect
HttpResponse response = client.execute(httppost);
// get response
HttpEntity entity = response.getEntity();
if(entity != null){
return EntityUtils.toString(entity);
}
else{
return "No string.";
}
}
catch(Exception e){
return "Network problem";
}
}
}
public void processFinish2 (String output2){
Toast.makeText(MainActivity.this,output2, Toast.LENGTH_SHORT).show();
try{
//str
JSONObject jsonResponse = new JSONObject(output2);
JSONArray aJson = jsonResponse.getJSONArray("gen_off");
// create apps list
for(int i=0; i<aJson.length(); i++) {
JSONObject json = aJson.getJSONObject(i);
//end
//str
String strCount = json.getString(TAG_COUNT);
count.setText(strCount);//setting name to original name text
//end
}
}catch (JSONException e) {
Toast.makeText(MainActivity.this,"Exception caught!", Toast.LENGTH_SHORT).show();
}
}
//end getting count
private void initView() {
// show progress dialog
// dialog = ProgressDialog.show(this, "", "Loading...");
String key="saasvaap123";
String signup_id="8";
String url = "http://gooffers.in/omowebservices/index.php/webservice/Public_User/saved_offers_list?";
FetchDataTask task = new FetchDataTask();
task.execute(url,key,signup_id);
}
public class FetchDataTask extends AsyncTask<String, Void, String>{
// private final FetchDataListener listener;
private String msg;
#Override
protected String doInBackground(String... params) {
if(params == null) return null;
// get url from params
String url = params[0];
String key1 = params[1];
String signupid1 = params[2];
ArrayList<NameValuePair> postParameters;
postParameters = new ArrayList<NameValuePair>();
postParameters.add(new BasicNameValuePair("key",key1));
postParameters.add(new BasicNameValuePair("signup_id",signupid1));
//str
try {
// create http connection
HttpClient client = new DefaultHttpClient();
HttpPost httppost = new HttpPost(url);
httppost.setEntity(new UrlEncodedFormEntity(postParameters));
// connect
HttpResponse response = client.execute(httppost);
// get response
HttpEntity entity = response.getEntity();
if(entity != null){
return EntityUtils.toString(entity);
}
else{
return "No string.";
}
}
catch(Exception e){
return "Network problem";
}
}
//end
//
#Override
protected void onPostExecute(String sJson) {
try {
JSONObject jsonResponse = new JSONObject(sJson);
JSONArray aJson = jsonResponse.getJSONArray("gen_off");
Toast.makeText(MainActivity.this, aJson.toString(),Toast.LENGTH_SHORT).show();
// create apps list
List<SavedOffers> apps = new ArrayList<SavedOffers>();
for(int i=0; i<aJson.length(); i++) {
JSONObject json = aJson.getJSONObject(i);
SavedOffers app = new SavedOffers();
app.setTitle(json.getString("title"));
app.setOriginalRate(json.getString("price"));
app.setOfferRate(json.getString("off_price"));
app.setPercentage(json.getString("percent"));
app.setSavings(json.getString("savings"));
app.setUrl(json.getString("image"));
// add the app to apps list
apps.add(app);
}
SavedOffersAdapter adapter = new SavedOffersAdapter(MainActivity.this, apps);
// set the adapter to list
l1.setAdapter(adapter);
//for delete
// adapter.notifyDataSetChanged();
/** Defining a click event listener for the button "Delete" */
Button btnDel = (Button) findViewById(R.id.deleteid);
OnClickListener listenerDel = new OnClickListener() {
#Override
public void onClick(View v) {
/** Getting the checked items from the listview */
SparseBooleanArray checkedItemPositions = l1.getCheckedItemPositions();
int itemCount = l1.getCount();
for(int i=itemCount-1; i >= 0; i--){
if(checkedItemPositions.get(i)){
adapter.remove(l1.get(i));
}
}
checkedItemPositions.clear();
adapter.notifyDataSetChanged();
}
};
/** Setting the event listener for the delete button */
btnDel.setOnClickListener(listenerDel);
/** Setting the adapter to the ListView */
l1.setAdapter(adapter); //end delete
//notify the activity that fetch data has been complete
// if(listener != null) listener.onFetchComplete(apps);
} catch (JSONException e) {
// msg = "Invalid response";
// if(listener != null) listener.onFetchFailure(msg);
// return;
}
}
/**
* This function will convert response stream into json string
* #param is respons string
* #return json string
* #throws IOException
*/
public String streamToString(final InputStream is) throws IOException{
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
StringBuilder sb = new StringBuilder();
String line = null;
try {
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
}
catch (IOException e) {
throw e;
}
finally {
try {
is.close();
}
catch (IOException e) {
throw e;
}
}
return sb.toString();
}
}
}
// this is my adapter class , I think change is only needed in main activity
// , I need to delete a specific list item from listview on clicking the delete button
public class SavedOffersAdapter extends ArrayAdapter<SavedOffers>{
private List<SavedOffers> items;
Bitmap bitmap;
ImageView image;
public SavedOffersAdapter(Context context, List<SavedOffers> items) {
super(context, R.layout.app_custom_list, items);
this.items = items;
}
#Override
public int getCount() {
return items.size();
}
private class ViewHolder {
//TextView laptopTxt;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
// ViewHolder holder;//added
View v = convertView;
if(v == null) {
LayoutInflater li = LayoutInflater.from(getContext());
v = li.inflate(R.layout.app_custom_list, null);
}
SavedOffers app = items.get(position);
if(app != null) {
TextView productName = (TextView)v.findViewById(R.id.nameid);
TextView originalRate = (TextView)v.findViewById(R.id.originalid);
originalRate.setPaintFlags(originalRate.getPaintFlags() | Paint.STRIKE_THRU_TEXT_FLAG);
TextView offerRate = (TextView)v.findViewById(R.id.offerid);
TextView percentage = (TextView)v.findViewById(R.id.discountid);
TextView savings = (TextView)v.findViewById(R.id.savingsid);
image =(ImageView)v.findViewById(R.id.prctimgid);
if(productName != null) productName.setText(app.getTitle());
if(originalRate != null) originalRate.setText(app.getOriginalRate());
if(offerRate != null) offerRate.setText(app. getOfferRate());
if(percentage != null) percentage.setText(app. getPercentage());
if(savings != null) savings.setText(app. getSavings());
if(image!=null){
new DownloadImageTask(image).execute(app.getUrl());
}
}
return v;
}
In your listviews adapter's getView method you link to the button on the layout your inflating and just attach a setOnClickListener... to the button and have it remove that item from your list or array that your adapter uses and then notifyDataHasChanged.
Delete that item from items in that position.
So 1. you want to delete the item from the ListView
2. you want to delete the item from the SQL DB.
The first one is very easy, but you kind of need to know the underlining adapter and how it serves data to your ListView. When you instantiate a BaseAdapter for the ListView you pass in a List or an array. This array will be the data your BaseAdapter serves to your ListView, each view in the listview will be showing an element from the array (done in getView()). If you dynamically delete one of those items, then adjust your array (or just use a List and it's .remove(), and finally notifyDataSetChanged(); your BaseAdapter will refresh your list without that View (or rather that View will be replaced with the new one). So for instance below I pass in a List<WeatherLocation> (WeatherLocation is a containing class that has weather stuff for a particular area (city, zipcode, degree"Biddeford", 04005, 72) to my BaseAdapter.
// Instantiate ListView
ListView lvLocations = (ListView) findViewById(R.id.lvLocations);
// Instantiate our BaseAdapter (pass in the List<WeatherLocation>)
WeatherLocationAdapter mWeatherLocationAdapter = new WeatherLocationAdapter(savedList, this, R.layout.view_weather_location);
lvLocations.setAdapter(mWeatherLocationAdapter);
This is an example of a regular ListView setting an Adapter to a custom BaseAdapter.
The BaseAdapter is so simple, that really the only method you care about (majorly) is the getView() method.
R.layout.view_weather_location is just a `LinearLayout` I made, it has 3 TextViews in it that I tie (show) my data with, by attaching data to those TextViews in the `getView()` method of the `BaseAdapter`. You would put a `Button there and tie it to what you want (to delete the data item)`.
public class WeatherLocationAdapter extends BaseAdapter{
private List <WeatherLocation> mLocations;
private Context mContext;
private int rowForLocationToInflate;
private LayoutInflater inflater;
public WeatherLocationAdapter(List<WeatherLocation> mLocations, Context mContext, int rowForLocationToInflate) {
this.mLocations = mLocations;
this.mContext = mContext;
this.rowForLocationToInflate = rowForLocationToInflate;
inflater = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
//TODO just built up layout now must tie to it.
private void addLocation(WeatherLocation newLocation){
mLocations.add(newLocation);
//TODO maybe invalidate after adding new item.
}
#Override
public int getCount() {
return mLocations.size();
}
#Override
public WeatherLocation getItem(int position) {
return mLocations.get(position);
}
#Override
public long getItemId(int position) {
return 0;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
//TODO build a viewholder
View rowView = inflater.inflate(rowForLocationToInflate, parent, false);
TextView tvZipcode = (TextView) rowView.findViewById(R.id.tvZipCode);
TextView tvCity = (TextView) rowView.findViewById(R.id.tvCity);
TextView tvTemp = (TextView) rowView.findViewById(R.id.tvDegree);
tvZipcode.setText(mLocations.get(position).getZipcode());
tvCity.setText(mLocations.get(position).getCity());
tvTemp.setText(String.valueOf(mLocations.get(position).getTemperature()));
// If you had a Button in your LinearLayout you were attaching to you that you wanted to delete that view/item with, it would look something like this in my case.
Button bDel = (Button) row.findViewById(R.id.bDel);
bDel.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mLocations.remove(position);
}
});
return rowView;
}
}
In the onClick you would also remove the item from the SQL db. I can show that too, but I feel you have some coding to do as it stands.

Using an interface from multiple async tasks

I have an interesting fragment with multiple spinners. THe first spinner, loads the data into the second spinner based on what was selected. It looks something like this:
When the fragment first loads the first spinner is "All" and it fills the listView with all the beers. Right now this is the only listView I can click on items without them force closing. The code for my portfolio is:
public class Portfolio extends Fragment implements PortfolioGetAllBeers.OnArticleSelectedListener {
String beerId = "";
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
//set layout here
final View theLayout = inflater.inflate(R.layout.activity_portfolio, container, false);
setHasOptionsMenu(true);
getActivity().setTitle("Portfolio");
//get user information
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(getActivity());
String userName = prefs.getString("userName", null);
String userID = prefs.getString("userID", null);
final Spinner portfolioType = (Spinner) theLayout.findViewById(R.id.portfolioSpinner);
portfolioType.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parentView, View selectedItemView, int position, long id) {
String portfolioChoice = portfolioType.getSelectedItem().toString();
Log.d("portfolio", portfolioChoice);
if( portfolioChoice.equals("All")){
//todo: clear second spinner
LinearLayout ll = (LinearLayout) theLayout.findViewById(R.id.addSpinnerLayout);
ll.removeAllViews();
//get userID
//get user data
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(selectedItemView.getContext());
String userID = prefs.getString("userID", null);
//construct url
String url = "myURL1";
//async task goes here
PortfolioGetAllBeers task = new PortfolioGetAllBeers(getActivity());
task.setOnArticleSelectedListener(Portfolio.this);
task.execute(url);
}
else if (portfolioChoice.equals("Brewery")){
LinearLayout ll = (LinearLayout) theLayout.findViewById(R.id.addSpinnerLayout);
ll.removeAllViews();
LayoutInflater inflater = (LayoutInflater)selectedItemView.getContext().getSystemService(selectedItemView.getContext().LAYOUT_INFLATER_SERVICE);
View v = inflater.inflate(R.layout.addspinner_layout, null); // inflate addspinner
Spinner sp = (Spinner) v.findViewById(R.id.portfolioSpinner2); //portfolioSpinner2
ll.addView(v); // add the view to the linear layout
//todo: get breweries and fill spinner
//get userID
//get user data
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(selectedItemView.getContext());
String userID = prefs.getString("userID", null);
//construct url
String url = ""myurl2;
//async task goes here
PortfolioGetAllBeers task = new PortfolioGetAllBeers(getActivity());
task.setOnArticleSelectedListener(Portfolio.this);
task.execute(url);
}
else if (portfolioChoice.equals("Style")){
LinearLayout ll = (LinearLayout) theLayout.findViewById(R.id.addSpinnerLayout);
ll.removeAllViews();
LayoutInflater inflater = (LayoutInflater)selectedItemView.getContext().getSystemService(selectedItemView.getContext().LAYOUT_INFLATER_SERVICE);
View v = inflater.inflate(R.layout.addspinner_layout, null); // inflate addspinner
Spinner sp = (Spinner) v.findViewById(R.id.portfolioSpinner2); //portfolioSpinner2
ll.addView(v); // add the view to the linear layout
//get userID
//get user data
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(selectedItemView.getContext());
String userID = prefs.getString("userID", null);
//construct url
String url = "myurl3";
//todo: async task goes here
new PortfolioGetAllStyles(selectedItemView.getContext()).execute(url);
}
else if (portfolioChoice.equals("Rating")){
LinearLayout ll = (LinearLayout) theLayout.findViewById(R.id.addSpinnerLayout);
ll.removeAllViews();
LayoutInflater inflater = (LayoutInflater)selectedItemView.getContext().getSystemService(selectedItemView.getContext().LAYOUT_INFLATER_SERVICE);
View v = inflater.inflate(R.layout.addspinner_layout, null); // inflate addspinner
Spinner sp = (Spinner) v.findViewById(R.id.portfolioSpinner2); //portfolioSpinner2
ll.addView(v); // add the view to the linear layout
//get userID
//get user data
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(selectedItemView.getContext());
String userID = prefs.getString("userID", null);
//make array
//make array list for beer
final List<String> tasteList = new ArrayList<String>();
tasteList.add("1");
tasteList.add("2");
tasteList.add("3");
tasteList.add("4");
tasteList.add("5");
// Selection of the spinner
Spinner spinner = (Spinner) theLayout.findViewById(R.id.portfolioSpinner2);
// Application of the Array to the Spinner
ArrayAdapter<String> spinnerArrayAdapter = new ArrayAdapter<String>(selectedItemView.getContext(), android.R.layout.simple_spinner_item,tasteList );
spinnerArrayAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); // The drop down view
spinner.setAdapter(spinnerArrayAdapter);
//todo: add on select for spinner 2
//add on item selected
final Spinner portfolioType = (Spinner) theLayout.findViewById(R.id.portfolioSpinner2);
portfolioType.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parentView, View selectedItemView, int position, long id) {
String portfolioChoice = portfolioType.getSelectedItem().toString();
//Toast.makeText(((Activity) c).getApplicationContext(), portfolioChoice, Toast.LENGTH_LONG).show();
final ListView lv = (ListView) theLayout.findViewById(R.id.allYourBeersList);
lv.setAdapter(null);
//get brewery beers
//get userID
//get user data
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(selectedItemView.getContext());
String userID = prefs.getString("userID", null);
try {
portfolioChoice = URLEncoder.encode(portfolioChoice, "UTF-8");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
//construct url
String url = "myurl4;
Log.d("portfolio" , url);
//async task goes here
new PortfolioGetAllBeers(selectedItemView.getContext()).execute(url);
}
#Override
public void onNothingSelected(AdapterView<?> parentView) {
// do nothing
}
});
}
}
#Override
public void onNothingSelected(AdapterView<?> parentView) {
// do nothing
}
});
// Inflate the layout for this fragment
return theLayout;
}
#Override
public void onArticleSelected(String bID, String brewery){
//code to execute on click
Fragment Fragment_one;
FragmentManager man= getFragmentManager();
FragmentTransaction tran = man.beginTransaction();
Fragment_one = new BeerPage();
final Bundle bundle = new Bundle();
bundle.putString("beerIDSent", bID);
bundle.putString("breweryIDSent", brewery);
Fragment_one.setArguments(bundle);
tran.replace(R.id.main, Fragment_one);//tran.
tran.addToBackStack(null);
tran.commit();
}
}
If the spinner is all on the first load it runs this portion of code from above:
if( portfolioChoice.equals("All")){
//todo: clear second spinner
LinearLayout ll = (LinearLayout) theLayout.findViewById(R.id.addSpinnerLayout);
ll.removeAllViews();
//get userID
//get user data
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(selectedItemView.getContext());
String userID = prefs.getString("userID", null);
//construct url
String url = "myURL1";
//async task goes here
PortfolioGetAllBeers task = new PortfolioGetAllBeers(getActivity());
task.setOnArticleSelectedListener(Portfolio.this);
task.execute(url);
}
Which calls this async task to load the listview:
public class PortfolioGetAllBeers extends AsyncTask<String, Void, String> {
Context c;
private ProgressDialog Dialog;
public PortfolioGetAllBeers (Context context)
{
c = context;
Dialog = new ProgressDialog(c);
}
#Override
protected String doInBackground(String... arg0) {
// TODO Auto-generated method stub
return readJSONFeed(arg0[0]);
}
protected void onPreExecute() {
Dialog.setMessage("Getting beers");
Dialog.setTitle("Loading");
Dialog.setCancelable(false);
Dialog.show();
}
//***************************code for on click
OnArticleSelectedListener listener;
public interface OnArticleSelectedListener{
public void onArticleSelected(String myString , String brewery);
}
public void setOnArticleSelectedListener(OnArticleSelectedListener listener){
this.listener = listener;
}
//*****************************end code for onClick
protected void onPostExecute(String result){
//decode json here
try{
JSONArray jsonArray = new JSONArray(result);
//acces listview
ListView lv = (ListView) ((Activity) c).findViewById(R.id.allYourBeersList);
//make array list for beer
final List<ShortBeerInfo> tasteList = new ArrayList<ShortBeerInfo>();
for(int i = 0; i < jsonArray.length(); i++) {
String beer = jsonArray.getJSONObject(i).getString("beer");
String rate = jsonArray.getJSONObject(i).getString("rate");
String beerID = jsonArray.getJSONObject(i).getString("id");
String bID = jsonArray.getJSONObject(i).getString("breweryID");
//create object
ShortBeerInfo tempTaste = new ShortBeerInfo(beer, rate, beerID, bID);
//add to arraylist
tasteList.add(tempTaste);
}
//add items to listview
ShortBeerInfoAdapter adapter1 = new ShortBeerInfoAdapter(c ,R.layout.brewer_stats_listview, tasteList);
lv.setAdapter(adapter1);
//set up clicks
lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1,
int arg2, long arg3) {
ShortBeerInfo o=(ShortBeerInfo)arg0.getItemAtPosition(arg2);
String tempID = o.id;
String tempBrewID = o.brewery;
//todo: go to beer page
listener.onArticleSelected(tempID, tempBrewID);
}
});
}
catch(Exception e){
}
Dialog.dismiss();
}
public String readJSONFeed(String URL) {
StringBuilder stringBuilder = new StringBuilder();
HttpClient httpClient = new DefaultHttpClient();
HttpGet httpGet = new HttpGet(URL);
try {
HttpResponse response = httpClient.execute(httpGet);
StatusLine statusLine = response.getStatusLine();
int statusCode = statusLine.getStatusCode();
if (statusCode == 200) {
HttpEntity entity = response.getEntity();
InputStream inputStream = entity.getContent();
BufferedReader reader = new BufferedReader(
new InputStreamReader(inputStream));
String line;
while ((line = reader.readLine()) != null) {
stringBuilder.append(line);
}
inputStream.close();
} else {
Log.d("JSON", "Failed to download file");
}
} catch (Exception e) {
Log.d("readJSONFeed", e.getLocalizedMessage());
}
return stringBuilder.toString();
}
}
When this loads the listview with items the onclicks work correctly through the interface. I am having trouble how to do the interface for the other options when the second spinner loads the data into the listview.
For example if you select style in the first spinner and an option in the second spinner as shown in the picture I posted above. It runs down this if statement in the code from Portfolio above:
else if (portfolioChoice.equals("Style")){
LinearLayout ll = (LinearLayout) theLayout.findViewById(R.id.addSpinnerLayout);
ll.removeAllViews();
LayoutInflater inflater = (LayoutInflater)selectedItemView.getContext().getSystemService(selectedItemView.getContext().LAYOUT_INFLATER_SERVICE);
View v = inflater.inflate(R.layout.addspinner_layout, null); // inflate addspinner
Spinner sp = (Spinner) v.findViewById(R.id.portfolioSpinner2); //portfolioSpinner2
ll.addView(v); // add the view to the linear layout
//get userID
//get user data
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(selectedItemView.getContext());
String userID = prefs.getString("userID", null);
//construct url
String url = "myurl3";
//todo: async task goes here
new PortfolioGetAllStyles(selectedItemView.getContext()).execute(url);
}
When PortfolioGetAllStyles asyc task is execute I am not sure how to set the onclick to the interface. The code for PortfolioGetAllStyles is:
public class PortfolioGetAllStyles extends AsyncTask<String, Void, String> {
Context c;
private ProgressDialog Dialog;
public PortfolioGetAllStyles (Context context)
{
c = context;
Dialog = new ProgressDialog(c);
}
#Override
protected String doInBackground(String... arg0) {
// TODO Auto-generated method stub
return readJSONFeed(arg0[0]);
}
protected void onPreExecute() {
Dialog.setMessage("Getting Brewery List");
Dialog.setTitle("Loading");
Dialog.setCancelable(false);
Dialog.show();
}
protected void onPostExecute(String result){
//decode json here
try{
JSONArray jsonArray = new JSONArray(result);
//acces listview
final ListView lv = (ListView) ((Activity) c).findViewById(R.id.allYourBeersList);
//make array list for beer
final List<String> tasteList = new ArrayList<String>();
for(int i = 0; i < jsonArray.length(); i++) {
String beer = jsonArray.getJSONObject(i).getString("style");
String bID = jsonArray.getJSONObject(i).getString("breweryID");
String rate = "na";
String beerID = "na";
//create object
ShortBeerInfo tempTaste = new ShortBeerInfo(beer, rate, beerID, bID);
//add to arraylist
tasteList.add(beer);
}
// Selection of the spinner
Spinner spinner = (Spinner) ((Activity) c).findViewById(R.id.portfolioSpinner2);
// Application of the Array to the Spinner
ArrayAdapter<String> spinnerArrayAdapter = new ArrayAdapter<String>(c, android.R.layout.simple_spinner_item,tasteList );
spinnerArrayAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); // The drop down view
spinner.setAdapter(spinnerArrayAdapter);
//add on item selected
final Spinner portfolioType = (Spinner) ((Activity) c).findViewById(R.id.portfolioSpinner2);
portfolioType.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parentView, View selectedItemView, int position, long id) {
String portfolioChoice = portfolioType.getSelectedItem().toString();
//Toast.makeText(((Activity) c).getApplicationContext(), portfolioChoice, Toast.LENGTH_LONG).show();
lv.setAdapter(null);
//get brewery beers
//get userID
//get user data
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(selectedItemView.getContext());
String userID = prefs.getString("userID", null);
try {
portfolioChoice = URLEncoder.encode(portfolioChoice, "UTF-8");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
//construct url
String url = "http://beerportfolio.com/app_getAllYourBeersStyle.php?u=" + userID + "&b=" + portfolioChoice;
Log.d("portfolio", url);
//async task goes here
new PortfolioGetAllBeers(selectedItemView.getContext()).execute(url);
}
#Override
public void onNothingSelected(AdapterView<?> parentView) {
// do nothing
}
});
}
catch(Exception e){
}
Dialog.dismiss();
}
public String readJSONFeed(String URL) {
StringBuilder stringBuilder = new StringBuilder();
HttpClient httpClient = new DefaultHttpClient();
HttpGet httpGet = new HttpGet(URL);
try {
HttpResponse response = httpClient.execute(httpGet);
StatusLine statusLine = response.getStatusLine();
int statusCode = statusLine.getStatusCode();
if (statusCode == 200) {
HttpEntity entity = response.getEntity();
InputStream inputStream = entity.getContent();
BufferedReader reader = new BufferedReader(
new InputStreamReader(inputStream));
String line;
while ((line = reader.readLine()) != null) {
stringBuilder.append(line);
}
inputStream.close();
} else {
Log.d("JSON", "Failed to download file");
}
} catch (Exception e) {
Log.d("readJSONFeed", e.getLocalizedMessage());
}
return stringBuilder.toString();
}
}
The error I am getting is:
03-03 14:30:00.495 20817-20817/com.beerportfolio.beerportfoliopro E/AndroidRuntime﹕ FATAL EXCEPTION: main
java.lang.NullPointerException
at com.beerportfolio.beerportfoliopro.PortfolioGetAllBeers$1.onItemClick(PortfolioGetAllBeers.java:114)
at android.widget.AdapterView.performItemClick(AdapterView.java:298)
at android.widget.AbsListView.performItemClick(AbsListView.java:1237)
at android.widget.ListView.performItemClick(ListView.java:4555)
at android.widget.AbsListView$PerformClick.run(AbsListView.java:3037)
at android.widget.AbsListView$1.run(AbsListView.java:3724)
at android.os.Handler.handleCallback(Handler.java:730)
at android.os.Handler.dispatchMessage(Handler.java:92)
at android.os.Looper.loop(Looper.java:158)
at android.app.ActivityThread.main(ActivityThread.java:5789)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:525)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1027)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:843)
at dalvik.system.NativeStart.main(Native Method)
In short I think I need to get these lines working to tie the OnSelectedListener from the portfolio page to this async task:
PortfolioGetAllBeers task = new PortfolioGetAllBeers(c);
task.setOnArticleSelectedListener(Portfolio.this);
task.execute(url);
I just can not pass Portfolio.this into that line since we are not in Portfolio but another async task launched from it.
It seems that in this line:
new PortfolioGetAllBeers(selectedItemView.getContext()).execute(url);
You are creating and triggering async task witout setting listener. So you should do one of the following things:
set listener always before executing created async task
check if listener is not null before calling it:
if(listener != null){
listener.onArticleSelected(tempID, tempBrewID);
}

trying to launch a fragment from an async task

I have an async task which is called for a fragment and populates a listview. When I try and set the OnClick for the listview I get an error in my code for setting the fragment to load based on the listview item clicked:
FragmentManager man= getFragmentManager();
FragmentTransaction tran=man.beginTransaction();
Fragment_one = new StylePage2();
final Bundle bundle = new Bundle();
bundle.putString("beerIDSent", bID);
Fragment_one.setArguments(bundle);
tran.replace(R.id.main, Fragment_one);//tran.
tran.addToBackStack(null);
tran.commit();
The error shows for the line:
FragmentManager man= getFragmentManager();
The error is, can not resolve method getFragmentManager()
I am assuming you can only access that method from within a fragment, so I am a bit lost on how to launch it from something that extends asynctask.
The full code for the async task is below:
public class GetStyleStatisticsJSON extends AsyncTask<String, Void, String> {
Context c;
private ProgressDialog Dialog;
android.support.v4.app.Fragment Fragment_one;
public GetStyleStatisticsJSON(Context context)
{
c = context;
Dialog = new ProgressDialog(c);
}
#Override
protected String doInBackground(String... arg0) {
// TODO Auto-generated method stub
return readJSONFeed(arg0[0]);
}
protected void onPreExecute() {
Dialog.setMessage("Analyzing Statistics");
Dialog.setTitle("Loading");
Dialog.setCancelable(false);
Dialog.show();
}
protected void onPostExecute(String result){
//decode json here
try{
JSONArray jsonArray = new JSONArray(result);
//acces listview
ListView lv = (ListView) ((Activity) c).findViewById(R.id.yourStyleStatistics);
//make array list for beer
final List<StyleInfo> tasteList = new ArrayList<StyleInfo>();
for(int i = 0; i < jsonArray.length(); i++) {
String style = jsonArray.getJSONObject(i).getString("style");
String rate = jsonArray.getJSONObject(i).getString("rate");
String beerID = jsonArray.getJSONObject(i).getString("id");
int count = i + 1;
style = count + ". " + style;
//create object
StyleInfo tempTaste = new StyleInfo(style, rate, beerID);
//add to arraylist
tasteList.add(tempTaste);
//add items to listview
StyleInfoAdapter adapter1 = new StyleInfoAdapter(c ,R.layout.brewer_stats_listview, tasteList);
lv.setAdapter(adapter1);
//set up clicks
lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1,
int arg2, long arg3) {
StyleInfo o=(StyleInfo)arg0.getItemAtPosition(arg2);
String bID = o.id;
//todo: add onclick for fragment to load
FragmentManager man= getFragmentManager();
FragmentTransaction tran=man.beginTransaction();
Fragment_one = new StylePage2();
final Bundle bundle = new Bundle();
bundle.putString("beerIDSent", bID);
Fragment_one.setArguments(bundle);
tran.replace(R.id.main, Fragment_one);//tran.
tran.addToBackStack(null);
tran.commit();
}
});
}
}
catch(Exception e){
}
Dialog.dismiss();
}
public String readJSONFeed(String URL) {
StringBuilder stringBuilder = new StringBuilder();
HttpClient httpClient = new DefaultHttpClient();
HttpGet httpGet = new HttpGet(URL);
try {
HttpResponse response = httpClient.execute(httpGet);
StatusLine statusLine = response.getStatusLine();
int statusCode = statusLine.getStatusCode();
if (statusCode == 200) {
HttpEntity entity = response.getEntity();
InputStream inputStream = entity.getContent();
BufferedReader reader = new BufferedReader(
new InputStreamReader(inputStream));
String line;
while ((line = reader.readLine()) != null) {
stringBuilder.append(line);
}
inputStream.close();
} else {
Log.d("JSON", "Failed to download file");
}
} catch (Exception e) {
Log.d("readJSONFeed", e.getLocalizedMessage());
}
return stringBuilder.toString();
}
}
UPDATE
I tried changing it to this:
FragmentManager man = ((Activity) c).getFragmentManager();
BUt I am getting this error:
Incompatible types.
Required:
android.support.v4.app.FragmentManager
Found:
android.app.FragmentManager
Update 2
I just tried this:
FragmentManager man= MainDraw.getFragmentManager();
and get this error:
Non-static method 'getFragmentManager()' cannot be referenced from a static context
It is very good practice to always create fragments from the holding activity only, so in this case what you would do is create a callback (interface) in your onclick to your activity that would create the fragment just like you would if you needed to communicate with your activity from your fragment.
doing this will fix your problem because Activity has getFragmentManager()
EDIT
OnArticleSelectedListener listener;
public interface OnArticleSelectedListener{
public void onArticleSelected(/*whatever you want to pass in it*/);
}
in your GetStyleStatisticsJSON create a method that sets the listener
public void setOnArticleSelectedListener(OnArticleSelectedListener listener){
this.listener = listener;
}
then in your onClick just call it
listener.onArticleSelected();
then declare your asynctask like this
GetStyleStatisticsJSON task = new GetStyleStatisticsJSON(getActvity());
task.setOnArticleSelectedListener(new OnArticleSelectedListener(){
#Override
public void onArticleSelected(){
}
});
task.execute(url)
Using
FragmentManager man= YourActivity.getFragmentManager();
instead of
FragmentManager man= getFragmentManager();

Force close when new fragment with async task is launched

I have a button that loads a new fragment but it is force closing with this error:
java.lang.NullPointerException
at com.beerportfolio.beerportfoliopro.BPTopTastes.onCreateView(BPTopTastes.java:29)
at android.support.v4.app.Fragment.performCreateView(Fragment.java:1500)
at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:927)
at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1104)
at android.support.v4.app.BackStackRecord.run(BackStackRecord.java:682)
at android.support.v4.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:1467)
at android.support.v4.app.FragmentManagerImpl$1.run(FragmentManager.java:440)
at android.os.Handler.handleCallback(Handler.java:730)
at android.os.Handler.dispatchMessage(Handler.java:92)
at android.os.Looper.loop(Looper.java:158)
at android.app.ActivityThread.main(ActivityThread.java:5789)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:525)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1027)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:843)
at dalvik.system.NativeStart.main(Native Method)
the button that loads the new fragment is this:
public class Discover extends Fragment {
Fragment Fragment_one;
Fragment Fragment_two;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.activity_discover, container, false);
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(getActivity());
String userName = prefs.getString("userName", null);
String userID = prefs.getString("userID", null);
//add button onclick fo top beers
Button bt = (Button)v.findViewById(R.id.discoverBeers);
bt.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// do whatever stuff you wanna do here
FragmentManager man=getFragmentManager();
FragmentTransaction tran=man.beginTransaction();
Fragment_one=new BPTopBeers();
tran.replace(R.id.main, Fragment_one);//tran.
tran.addToBackStack(null);
tran.commit();
}
});
//todo: add button onclick fo top tastes
Button bt2 = (Button)v.findViewById(R.id.discoverTaste);
bt2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// do whatever stuff you wanna do here
FragmentManager man=getFragmentManager();
FragmentTransaction tran=man.beginTransaction();
Fragment_two=new BPTopTastes();
tran.replace(R.id.main, Fragment_two);//tran.
tran.addToBackStack(null);
tran.commit();
}
});
// Inflate the layout for this fragment
//todo: change to discover layout
return v;
}
the fragment that is being launched is:
public class BPTopTastes extends Fragment {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.taste_statistics_layout, container, false);
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(getActivity());
String userName = prefs.getString("userName", null);
String userID = prefs.getString("userID", null);
String title = "Top Tastes on Beer Portfolio";
TextView topTitle = (TextView) v.findViewById(R.id.topTasteTitle);
topTitle.setText(title);
//construct url
String url = "myURL";
//async task goes here
new GetTasteStatisticsJSON(getActivity()).execute(url);
// Inflate the layout for this fragment
return v;
}
}
and the async task which is being called is:
public class GetTasteStatisticsJSON extends AsyncTask<String, Void, String> {
Context c;
private ProgressDialog Dialog;
public GetTasteStatisticsJSON(Context context)
{
c = context;
Dialog = new ProgressDialog(c);
}
#Override
protected String doInBackground(String... arg0) {
// TODO Auto-generated method stub
return readJSONFeed(arg0[0]);
}
protected void onPreExecute() {
Dialog.setMessage("Getting tastes");
Dialog.setTitle("Loading");
Dialog.setCancelable(false);
Dialog.show();
}
protected void onPostExecute(String result){
//decode json here
try{
JSONArray jsonArray = new JSONArray(result);
//acces listview
ListView lv = (ListView) ((Activity) c).findViewById(R.id.yourTasteStatistics);
//make array list for beer
final List<TasteInfo> tasteList = new ArrayList<TasteInfo>();
for(int i = 0; i < jsonArray.length(); i++) {
String style = jsonArray.getJSONObject(i).getString("taste");
String rate = jsonArray.getJSONObject(i).getString("rate");
int count = i + 1;
style = count + ". " + style;
Log.d("brewery stats", style);
//create object
TasteInfo tempTaste = new TasteInfo(style, rate);
//add to arraylist
tasteList.add(tempTaste);
//add items to listview
TasteInfoAdapter adapter1 = new TasteInfoAdapter(c ,R.layout.brewer_stats_listview, tasteList);
lv.setAdapter(adapter1);
//set up clicks
lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1,
int arg2, long arg3) {
TasteInfo o=(TasteInfo)arg0.getItemAtPosition(arg2);
String tempTaste = o.taste;
//todo: load taste page fragment
//Intent myIntent = new Intent(c, TastePage.class);
// myIntent.putExtra("taste", tempTaste);
//c.startActivity(myIntent);
}
});
}
}
catch(Exception e){
}
Dialog.dismiss();
}
public String readJSONFeed(String URL) {
StringBuilder stringBuilder = new StringBuilder();
HttpClient httpClient = new DefaultHttpClient();
HttpGet httpGet = new HttpGet(URL);
try {
HttpResponse response = httpClient.execute(httpGet);
StatusLine statusLine = response.getStatusLine();
int statusCode = statusLine.getStatusCode();
if (statusCode == 200) {
HttpEntity entity = response.getEntity();
InputStream inputStream = entity.getContent();
BufferedReader reader = new BufferedReader(
new InputStreamReader(inputStream));
String line;
while ((line = reader.readLine()) != null) {
stringBuilder.append(line);
}
inputStream.close();
} else {
Log.d("JSON", "Failed to download file");
}
} catch (Exception e) {
Log.d("readJSONFeed", e.getLocalizedMessage());
}
return stringBuilder.toString();
}
}
I am a bit confused cause I have another button in the same fragment that launches a new fragment in a similar way just fine...
I just noticed my mistake after combing through my code. I have the wrong id here in this line:
TextView topTitle = (TextView) v.findViewById(R.id.topTasteTitle);
so it could not find that, to set the title.
Can you check the BPTopTastes layout is inflating correctly, and hence topTitle is not null when you call the setText() method on it.
Does it work when you remove the async task ?
The Eclipse debugger can be set to halt on exception which might give you some pointers.

Categories

Resources