i got trouble, im try convert my fragment into activity, and when im try running the apps, all data not load and no warning or error shown, pls someone help
import android.app.Dialog;
import android.app.ProgressDialog;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.TextView;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.VolleyLog;
import com.android.volley.toolbox.ImageLoader;
import com.android.volley.toolbox.JsonArrayRequest;
import com.android.volley.toolbox.NetworkImageView;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.List;
public class RekomendasiExercise extends AppCompatActivity implements AdapterView.OnItemClickListener{
// Log tag
private static final String TAG = AbdominalFragment.class.getSimpleName();
// Movies json url
private static final String url = "http://......";
private ProgressDialog pDialog;
private List<Exercise> exerciseList = new ArrayList<Exercise>();
private ListView listView;
private CustomListAdapter adapter;
public RekomendasiExercise() {
// Required empty public constructor
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public void onDestroy() {
super.onDestroy();
hidePDialog();
}
private void hidePDialog() {
if (pDialog != null) {
pDialog.dismiss();
pDialog = null;
}
}
public View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.activity_list, container, false);
// Inflate the layout for this fragment
final ListView listView = (ListView) rootView.findViewById(R.id.list);
adapter = new CustomListAdapter(this, exerciseList);
listView.setAdapter(adapter);
pDialog = new ProgressDialog(this);
// Showing progress dialog before making http request
pDialog.setMessage("Loading...");
pDialog.show();
if(exerciseList.isEmpty()) {
// Creating volley request obj
JsonArrayRequest exerciseReq = new JsonArrayRequest(url,
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
Log.d(TAG, response.toString());
hidePDialog();
exerciseList.clear();
// Parsing json
for (int i = 0; i < response.length(); i++) {
try {
JSONObject obj = response.getJSONObject(i);
Exercise exercise = new Exercise();
if (obj.getString("tipe").equals("abdominal")) {
exercise.setNama(obj.getString("nama"));
exercise.setGambar1(obj.getString("gambar1"));
// Genre is json array
// adding movie to movies array
exerciseList.add(exercise);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
// notifying list adapter about data changes
// so that it renders the list view with updated data
adapter.notifyDataSetChanged();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d(TAG, "Error: " + error.getMessage());
hidePDialog();
}
});
// Adding request to request queue
AppController.getInstance().addToRequestQueue(exerciseReq);
}else{
hidePDialog();
}
listView.setOnItemClickListener(this);
return rootView;
}
#Override
public void onItemClick(AdapterView<?> parent, View convertView, int position, long id) {
// Create custom dialog object
final Dialog dialog = new Dialog(this);
// Include dialog.xml file
dialog.setContentView(R.layout.dialog); // layout of your dialog
ImageLoader imageLoader = AppController.getInstance().getImageLoader();
NetworkImageView thumbnail1 = (NetworkImageView ) dialog.findViewById(R.id.gambar1);
thumbnail1.setImageUrl(exerciseList.get(position).getGambar1(), imageLoader);
// Set dialog title
dialog.setTitle("Detail");
// set values for custom dialog components - text, image and button
TextView nama = (TextView) dialog.findViewById(R.id.nama);
nama.setText("Nama = " + exerciseList.get(position).getNama());
dialog.show();
}
}
if default in Fragment its running perfectly and no problem, but when im try using activity all data not load.
I can't see any code that would run when the activity is created. You have an onCreateView method (which I am guessing you are carrying over from your Fragment based implementation). Unless somewhere in your code (which I cannot see how) you are calling that method, it never gets called since it is not part of the Activity lifecycle. I would copy over the entire code from that method to onCreate method (as a starting point) and delete the method. I would then make the following changes to the first few lines
// View rootView = inflater.inflate(R.layout.activity_list, container, false);
// Noticed that I commented out the above line and changed the line below
final ListView listView = (ListView) findViewById(R.id.list);
I am not suggesting that this will solve all of your problems as there might be (likely) other issues, but you should potentially be the first step. I strongly suggest you get more familiar with the Activity and Fragment classes and become more comfortable with their lifecycles. Also, you should get rid of
public RekomendasiExercise() {
// Required empty public constructor
}
Best of luck
Related
im still confused about to get spinner item text.
So, In Activity.class i want to get Spinner Item Text from Fragment.class but idk how to get Spinner Item Text from fragment,
anyone can help?
Fragment.class
final Spinner spinner = (Spinner) rootView.findViewById(R.id.choices);
spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View v,
int postion, long arg3) {
// TODO Auto-generated method stub
String SpinerValue3 = parent.getItemAtPosition(postion).toString();
if (SpinerValue3.equals("Item 1")) {
Toast.makeText(getActivity().getBaseContext(),
"Try Choose : " + SpinerValue3,
Toast.LENGTH_SHORT).show();=
} else if (SpinerValue3.equals("Item 2")) {
Toast.makeText(getActivity().getBaseContext(),
"Try Choose : " + SpinerValue3,
Toast.LENGTH_SHORT).show();
}else if (SpinerValue3.equals("Item 3")) {
Toast.makeText(getActivity().getBaseContext(),
"Try Choose : " + SpinerValue3,
Toast.LENGTH_SHORT).show();
}else if (SpinerValue3.equals("Item 4")) {
Toast.makeText(getActivity().getBaseContext(),
"Try Choose : " + SpinerValue3,
Toast.LENGTH_SHORT).show();
}else if (SpinerValue3.equals("Item 5")) {
Toast.makeText(getActivity().getBaseContext(),
"Try Choose : " + SpinerValue3,
Toast.LENGTH_SHORT).show();
}else if (SpinerValue3.equals("Item 6")) {
Toast.makeText(getActivity().getBaseContext(),
"Try Choose : " + SpinerValue3,
Toast.LENGTH_SHORT).show();
}
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
});
if above im explain for make a toast, but how to get text spinner item on Activity.class
Activity.class Iwant to change SPINNERITEM (On code below) with get Spinner item text from Fragment
import android.app.Dialog;
import android.app.ProgressDialog;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.CheckBox;
import android.widget.ListView;
import android.widget.Spinner;
import android.widget.TextView;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.VolleyLog;
import com.android.volley.toolbox.ImageLoader;
import com.android.volley.toolbox.JsonArrayRequest;
import com.android.volley.toolbox.NetworkImageView;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.List;
public class RekomendasiExercise extends AppCompatActivity implements AdapterView.OnItemClickListener{
// Log tag
private static final String TAG = AbdominalFragment.class.getSimpleName();
private static final String url = "http://........php";
private ProgressDialog pDialog;
private List<Exercise> exerciseList = new ArrayList<Exercise>();
private ListView listView;
private CustomListAdapter adapter;
public RekomendasiExercise() {
// Required empty public constructor
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_list);
final ListView listView = (ListView)findViewById(R.id.list);
final Spinner spinner = (Spinner) findViewById(R.id.choices);
adapter = new CustomListAdapter(this, exerciseList);
listView.setAdapter(adapter);
pDialog = new ProgressDialog(this);
// Showing progress dialog before making http request
pDialog.setMessage("Loading...");
pDialog.show();
if(exerciseList.isEmpty()) {
// Creating volley request obj
JsonArrayRequest exerciseReq = new JsonArrayRequest(url,
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
Log.d(TAG, response.toString());
hidePDialog();
exerciseList.clear();
// Parsing json
for (int i = 0; i < response.length(); i++) {
try {
String text = spinner.getSelectedItem().toString();
int positionitem = spinner.getSelectedItemPosition();
JSONObject obj = response.getJSONObject(i);
Exercise exercise = new Exercise();
if (obj.getString("type").equals("SPINNERITEM")) {
exercise.setNama(obj.getString("name"));
exercise.setTipe(obj.getString("type"));
exercise.setMainmuscle(obj.getString("mainmuscle"));
exerciseList.add(exercise);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
// notifying list adapter about data changes
// so that it renders the list view with updated data
adapter.notifyDataSetChanged();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d(TAG, "Error: " + error.getMessage());
hidePDialog();
}
});
// Adding request to request queue
AppController.getInstance().addToRequestQueue(exerciseReq);
}else{
hidePDialog();
}
listView.setOnItemClickListener(this);
}
#Override
public void onDestroy() {
super.onDestroy();
hidePDialog();
}
private void hidePDialog() {
if (pDialog != null) {
pDialog.dismiss();
pDialog = null;
}
}
#Override
public void onItemClick(AdapterView<?> parent, View convertView, int position, long id) {
// Create custom dialog object
final Dialog dialog = new Dialog(this);
// Include dialog.xml file
dialog.setContentView(R.layout.dialog); // layout of your dialog
// Set dialog title
dialog.setTitle("Detail");
// set values for custom dialog components - text, image and button
TextView nama = (TextView) dialog.findViewById(R.id.nama);
nama.setText("Nama = " + exerciseList.get(position).getNama());
// similar add statements for other details
dialog.show();
}
}
My recommendation would be to follow the standard communication model for Activity and Fragment where the Activity implements a callback interface defined in the Fragment.
Check this link for details.
In your onItemSelected method of the spinner, you can call the callback method of the Activity with the selected spinner value.
This is how you could do in OOPS ways
Step 1) Make a spinner Item Value variable in Activity Class
public class RekomendasiExercise extends AppCompatActivity implements AdapterView.OnItemClickListener{
private String currentSpinnerItem ;
/*
set current spinner item value
*/
public void setCurrentSpinnerItem(String itemValue)
{
this.currentSpinnerItem = itemValue ;
//Do stuffs in activity with new value
}
Step 2) Now in your fragment class update currentItemSpinner value like this
#Override
public void onItemSelected(AdapterView<?> parent, View v,
int postion, long arg3) {
String SpinerValue3 = parent.getItemAtPosition(postion).toString();
//Update spinner selected item value in activity
((RekomendasiExercise) getActivity).setCurrentSpinnerItem(SpinerValue3);
}
I am trying to convert my Fragment Code to Activity code, but when I try to run the Activity, the Activity opens but the data is null. Here my code
Fragment
import android.app.Activity;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.TextView;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.VolleyLog;
import com.android.volley.toolbox.ImageLoader;
import com.android.volley.toolbox.JsonArrayRequest;
import com.android.volley.toolbox.NetworkImageView;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.List;
public class ArmBicepFragment extends Fragment implements AdapterView.OnItemClickListener {
// Log tag
private static final String TAG = ArmBicepFragment.class.getSimpleName();
// Movies json url
private static final String url = "http:.......";
private ProgressDialog pDialog;
private List<Exercise> exerciseList = new ArrayList<Exercise>();
private ListView listView;
private CustomListAdapter adapter;
public ArmBicepFragment() {
// Required empty public constructor
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public void onDestroy() {
super.onDestroy();
hidePDialog();
}
private void hidePDialog() {
if (pDialog != null) {
pDialog.dismiss();
pDialog = null;
}
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.activity_list, container, false);
// Inflate the layout for this fragment
final ListView listView = (ListView) rootView.findViewById(R.id.list);
adapter = new CustomListAdapter(getActivity(), exerciseList);
listView.setAdapter(adapter);
pDialog = new ProgressDialog(getActivity());
// Showing progress dialog before making http request
pDialog.setMessage("Loading...");
pDialog.show();
if(exerciseList.isEmpty()) {
// Creating volley request obj
JsonArrayRequest exerciseReq = new JsonArrayRequest(url,
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
Log.d(TAG, response.toString());
hidePDialog();
exerciseList.clear();
// Parsing json
for (int i = 0; i < response.length(); i++) {
try {
JSONObject obj = response.getJSONObject(i);
Exercise exercise = new Exercise();
if (obj.getString("name").equals("bicep")) {
exercise.setNama(obj.getString("nama"));
exercise.setGambar1(obj.getString("gambar1"));
// Genre is json array
exerciseList.add(exercise);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
// notifying list adapter about data changes
// so that it renders the list view with updated data
adapter.notifyDataSetChanged();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d(TAG, "Error: " + error.getMessage());
hidePDialog();
}
});
// Adding request to request queue
AppController.getInstance().addToRequestQueue(exerciseReq);
}else{
hidePDialog();
}
listView.setOnItemClickListener(this);
return rootView;
}
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
}
#Override
public void onDetach() {
super.onDetach();
}
#Override
public void onItemClick(AdapterView<?> parent, View convertView, int position, long id) {
// Create custom dialog object
final Dialog dialog = new Dialog(getContext());
// Include dialog.xml file
dialog.setContentView(R.layout.dialog); // layout of your dialog
ImageLoader imageLoader = AppController.getInstance().getImageLoader();
NetworkImageView thumbnail1 = (NetworkImageView ) dialog.findViewById(R.id.gambar1);
thumbnail1.setImageUrl(exerciseList.get(position).getGambar1(), imageLoader);
// Set dialog title
dialog.setTitle("Detail");
// set values for custom dialog components - text, image and button
TextView nama = (TextView) dialog.findViewById(R.id.nama);
nama.setText("Nama = " + exerciseList.get(position).getNama());
// similar add statements for other details
dialog.show();
}
}
And here my convert result from Fragment (Nothing Error or warning)
import android.app.Dialog;
import android.app.ProgressDialog;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.TextView;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.VolleyLog;
import com.android.volley.toolbox.ImageLoader;
import com.android.volley.toolbox.JsonArrayRequest;
import com.android.volley.toolbox.NetworkImageView;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.List;
/**
* Created by Felix on 5/15/2016.
*/
public class RekomendasiExercise extends AppCompatActivity implements AdapterView.OnItemClickListener{
// Log tag
private static final String TAG = AbdominalFragment.class.getSimpleName();
// Movies json url
private static final String url = "http:............";
private ProgressDialog pDialog;
private List<Exercise> exerciseList = new ArrayList<Exercise>();
private ListView listView;
private CustomListAdapter adapter;
public RekomendasiExercise() {
// Required empty public constructor
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public void onDestroy() {
super.onDestroy();
hidePDialog();
}
private void hidePDialog() {
if (pDialog != null) {
pDialog.dismiss();
pDialog = null;
}
}
public View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.activity_list, container, false);
// Inflate the layout for this fragment
final ListView listView = (ListView) rootView.findViewById(R.id.list);
adapter = new CustomListAdapter(this, exerciseList);
listView.setAdapter(adapter);
pDialog = new ProgressDialog(this);
// Showing progress dialog before making http request
pDialog.setMessage("Loading...");
pDialog.show();
if(exerciseList.isEmpty()) {
// Creating volley request obj
JsonArrayRequest exerciseReq = new JsonArrayRequest(url,
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
Log.d(TAG, response.toString());
hidePDialog();
exerciseList.clear();
// Parsing json
for (int i = 0; i < response.length(); i++) {
try {
JSONObject obj = response.getJSONObject(i);
Exercise exercise = new Exercise();
if (obj.getString("nama").equals("abdominal")) {
exercise.setNama(obj.getString("nama"));
exercise.setGambar1(obj.getString("gambar1"));
// Genre is json array
// adding movie to movies array
exerciseList.add(exercise);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
// notifying list adapter about data changes
// so that it renders the list view with updated data
adapter.notifyDataSetChanged();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d(TAG, "Error: " + error.getMessage());
hidePDialog();
}
});
// Adding request to request queue
AppController.getInstance().addToRequestQueue(exerciseReq);
}else{
hidePDialog();
}
listView.setOnItemClickListener(this);
return rootView;
}
#Override
public void onItemClick(AdapterView<?> parent, View convertView, int position, long id) {
// Create custom dialog object
final Dialog dialog = new Dialog(this);
// Include dialog.xml file
dialog.setContentView(R.layout.dialog); // layout of your dialog
ImageLoader imageLoader = AppController.getInstance().getImageLoader();
NetworkImageView thumbnail1 = (NetworkImageView ) dialog.findViewById(R.id.gambar1);
thumbnail1.setImageUrl(exerciseList.get(position).getGambar1(), imageLoader);
// Set dialog title
dialog.setTitle("Detail");
// set values for custom dialog components - text, image and button
TextView nama = (TextView) dialog.findViewById(R.id.nama);
nama.setText("Nama = " + exerciseList.get(position).getNama());
// similar add statements for other details
dialog.show();
}
}
onCreateView
is not a part of activity's lifecycle. You need to move stuff from this method to onCreate:
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_list);
final ListView listView = (ListView) findViewById(R.id.list);
adapter = new CustomListAdapter(this, exerciseList);
listView.setAdapter(adapter);
pDialog = new ProgressDialog(this);
// Showing progress dialog before making http request
pDialog.setMessage("Loading...");
pDialog.show();
if(exerciseList.isEmpty()) {
// Creating volley request obj
JsonArrayRequest exerciseReq = new JsonArrayRequest(url,
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
Log.d(TAG, response.toString());
hidePDialog();
exerciseList.clear();
// Parsing json
for (int i = 0; i < response.length(); i++) {
try {
JSONObject obj = response.getJSONObject(i);
Exercise exercise = new Exercise();
if (obj.getString("nama").equals("abdominal")) {
exercise.setNama(obj.getString("nama"));
exercise.setGambar1(obj.getString("gambar1"));
// Genre is json array
// adding movie to movies array
exerciseList.add(exercise);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
// notifying list adapter about data changes
// so that it renders the list view with updated data
adapter.notifyDataSetChanged();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d(TAG, "Error: " + error.getMessage());
hidePDialog();
}
});
// Adding request to request queue
AppController.getInstance().addToRequestQueue(exerciseReq);
}else{
hidePDialog();
}
listView.setOnItemClickListener(this);
}
You should put your codes in onCreate . Copy/paste the below codes.
public class RekomendasiExercise extends AppCompatActivity implements AdapterView.OnItemClickListener{
// Log tag
private static final String TAG = AbdominalFragment.class.getSimpleName();
// Movies json url
private static final String url = "http:............";
private ProgressDialog pDialog;
private List<Exercise> exerciseList = new ArrayList<Exercise>();
private ListView listView;
private CustomListAdapter adapter;
public RekomendasiExercise() {
// Required empty public constructor
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_list);
final ListView listView = (ListView)findViewById(R.id.list);
adapter = new CustomListAdapter(this, exerciseList);
listView.setAdapter(adapter);
pDialog = new ProgressDialog(this);
// Showing progress dialog before making http request
pDialog.setMessage("Loading...");
pDialog.show();
if(exerciseList.isEmpty()) {
// Creating volley request obj
JsonArrayRequest exerciseReq = new JsonArrayRequest(url,
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
Log.d(TAG, response.toString());
hidePDialog();
exerciseList.clear();
// Parsing json
for (int i = 0; i < response.length(); i++) {
try {
JSONObject obj = response.getJSONObject(i);
Exercise exercise = new Exercise();
if (obj.getString("nama").equals("abdominal")) {
exercise.setNama(obj.getString("nama"));
exercise.setGambar1(obj.getString("gambar1"));
// Genre is json array
// adding movie to movies array
exerciseList.add(exercise);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
// notifying list adapter about data changes
// so that it renders the list view with updated data
adapter.notifyDataSetChanged();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d(TAG, "Error: " + error.getMessage());
hidePDialog();
}
});
// Adding request to request queue
AppController.getInstance().addToRequestQueue(exerciseReq);
}else{
hidePDialog();
}
listView.setOnItemClickListener(this);
}
#Override
public void onDestroy() {
super.onDestroy();
hidePDialog();
}
private void hidePDialog() {
if (pDialog != null) {
pDialog.dismiss();
pDialog = null;
}
}
public View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState) {
}
#Override
public void onItemClick(AdapterView<?> parent, View convertView, int position, long id) {
// Create custom dialog object
final Dialog dialog = new Dialog(this);
// Include dialog.xml file
dialog.setContentView(R.layout.dialog); // layout of your dialog
ImageLoader imageLoader = AppController.getInstance().getImageLoader();
NetworkImageView thumbnail1 = (NetworkImageView ) dialog.findViewById(R.id.gambar1);
thumbnail1.setImageUrl(exerciseList.get(position).getGambar1(), imageLoader);
// Set dialog title
dialog.setTitle("Detail");
// set values for custom dialog components - text, image and button
TextView nama = (TextView) dialog.findViewById(R.id.nama);
nama.setText("Nama = " + exerciseList.get(position).getNama());
// similar add statements for other details
dialog.show();
}
}
import android.app.Activity;
import android.app.Dialog;
import android.app.ProgressDialog;
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.ListView;
import android.widget.TextView;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.VolleyLog;
import com.android.volley.toolbox.ImageLoader;
import com.android.volley.toolbox.JsonArrayRequest;
import com.android.volley.toolbox.NetworkImageView;
import com.elite.youvaa.R;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.List;
public class ArmBicepFragment extends Activity implements AdapterView.OnItemClickListener {
// Log tag
private static final String TAG = ArmBicepFragment.class.getSimpleName();
// Movies json url
private static final String url = "http:.......";
private ProgressDialog pDialog;
private List<Exercise> exerciseList = new ArrayList<Exercise>();
private ListView listView;
private CustomListAdapter adapter;
public ArmBicepFragment() {
// Required empty public constructor
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_list);
final ListView listView = (ListView)findViewById(R.id.list);
adapter = new CustomListAdapter(getApplicationContext(), exerciseList);
listView.setAdapter(adapter);
pDialog = new ProgressDialog(getApplicationContext());
// Showing progress dialog before making http request
pDialog.setMessage("Loading...");
pDialog.show();
if(exerciseList.isEmpty()) {
// Creating volley request obj
JsonArrayRequest exerciseReq = new JsonArrayRequest(url,
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
Log.d(TAG, response.toString());
hidePDialog();
exerciseList.clear();
// Parsing json
for (int i = 0; i < response.length(); i++) {
try {
JSONObject obj = response.getJSONObject(i);
Exercise exercise = new Exercise();
if (obj.getString("name").equals("bicep")) {
exercise.setNama(obj.getString("nama"));
exercise.setGambar1(obj.getString("gambar1"));
// Genre is json array
exerciseList.add(exercise);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
// notifying list adapter about data changes
// so that it renders the list view with updated data
adapter.notifyDataSetChanged();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d(TAG, "Error: " + error.getMessage());
hidePDialog();
}
});
// Adding request to request queue
AppController.getInstance().addToRequestQueue(exerciseReq);
}else{
hidePDialog();
}
listView.setOnItemClickListener(this);
}
#Override
public void onDestroy() {
super.onDestroy();
hidePDialog();
}
private void hidePDialog() {
if (pDialog != null) {
pDialog.dismiss();
pDialog = null;
}
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.activity_list, container, false);
// Inflate the layout for this fragment
return rootView;
}
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
}
#Override
public void onDetach() {
super.onDetach();
}
#Override
public void onItemClick(AdapterView<?> parent, View convertView, int position, long id) {
// Create custom dialog object
final Dialog dialog = new Dialog(getContext());
// Include dialog.xml file
dialog.setContentView(R.layout.dialog); // layout of your dialog
ImageLoader imageLoader = AppController.getInstance().getImageLoader();
NetworkImageView thumbnail1 = (NetworkImageView ) dialog.findViewById(R.id.gambar1);
thumbnail1.setImageUrl(exerciseList.get(position).getGambar1(), imageLoader);
// Set dialog title
dialog.setTitle("Detail");
// set values for custom dialog components - text, image and button
TextView nama = (TextView) dialog.findViewById(R.id.nama);
nama.setText("Nama = " + exerciseList.get(position).getNama());
// similar add statements for other details
dialog.show();
}
}
I have two activities...In first activity its a list view where i get the data from the Json file....now when user click on an item of the list view a new activity should open...so i pass the id from activity 1 to activity 2 using an intent. Instead of sending all the details using intent is there any other way that i can only pass the id to activity 2 and then query json file to get details (json object) and then update the UI.
Here is my code.
Activity 1:-
package activity;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.AdapterView.OnItemClickListener;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.VolleyLog;
import com.android.volley.toolbox.JsonArrayRequest;
import com.android.volley.toolbox.NetworkImageView;
/**
* Created by on 11/25/15.
*/
public class ProductsList extends Activity {
// Log tag
private static final String TAG = ProductsList.class.getSimpleName();
// Movies json url
// private static final String url = "http://*.*.*.*:0000/android_login_api/toys.json"; //home
private static final String url = "http://*.*.*.*:0000/android_login_api/toys.json"; //starbucks
private ProgressDialog pDialog;
private List<Movie> movieList = new ArrayList<Movie>();
private ListView listView;
private CustomListAdapter adapter;
// Search EditText
EditText inputSearch;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.products_list_view);
listView = (ListView) findViewById(R.id.list);
inputSearch = (EditText) findViewById(R.id.inputSearch);
adapter = new CustomListAdapter(this, movieList);
listView.setAdapter(adapter);
listView.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View v, int position, long id) {
Movie item = (Movie) adapter.getItem(position);
Intent intent = new Intent(ProductsList.this, ProductDetailInformation.class);
intent.putExtra("id", item.getId().toString());
// intent.putExtra("name", item.getTitle().toString());
// intent.putExtra("price", item.getPrice().toString());
// Bundle reviews = new Bundle();
// reviews.putDouble("rating", ((Number) item.getRating()).doubleValue());
// intent.putExtras(reviews);
// intent.putExtra("description", item.getDescription().toString());
//
// //send image
// BitmapDrawable bd = (BitmapDrawable) ((NetworkImageView) v.findViewById(R.id.thumbnail))
// .getDrawable();
// Bitmap bitmap=bd.getBitmap();
// ByteArrayOutputStream baos = new ByteArrayOutputStream();
// bd.getBitmap().compress(Bitmap.CompressFormat.PNG, 100, baos);
// byte[] imgByte = baos.toByteArray();
// intent.putExtra("image", imgByte);
//based on item add info to intent
startActivity(intent);
}
});
pDialog = new ProgressDialog(this);
// Showing progress dialog before making http request
pDialog.setMessage("Loading...");
pDialog.show();
// // changing action bar color
// getActionBar().setBackgroundDrawable(
// new ColorDrawable(Color.parseColor("#1b1b1b")));
// Creating volley request obj
JsonArrayRequest movieReq = new JsonArrayRequest(url,
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
Log.d(TAG, response.toString());
hidePDialog();
// Parsing json
for (int i = 0; i < response.length(); i++) {
try {
JSONObject obj = response.getJSONObject(i);
Movie movie = new Movie();
movie.setTitle(obj.getString("title"));
movie.setThumbnailUrl(obj.getString("image"));
movie.setRating(((Number) obj.get("rating"))
.doubleValue());
movie.setAddtocart(obj.getInt("addtocart"));
movie.setDescription(obj.getString("description"));
movie.setId(obj.getString("id"));
// movie.setThumbnailUrl(obj.getString("image1"));
// Price is json array
// JSONArray priceArry = obj.getInt("price");
// ArrayList<String> price = new ArrayList<String>();
// for (int j = 0; j < priceArry.length(); j++) {
// price.add((String) priceArry.get(j));
// }
movie.setPrice(obj.getString("price"));
// adding movie to movies array
movieList.add(movie);
} catch (JSONException e) {
e.printStackTrace();
}
}
// notifying list adapter about data changes
// so that it renders the list view with updated data
adapter.notifyDataSetChanged();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d(TAG, "Error: " + error.getMessage());
hidePDialog();
}
});
// Adding request to request queue
AppController.getInstance().addToRequestQueue(movieReq);
/**
* Enabling Search Filter
* */
inputSearch.addTextChangedListener(new TextWatcher() {
#Override
public void onTextChanged(CharSequence cs, int arg1, int arg2, int arg3) {
// When user changed the Text
//ProductsList.this.listView.getFilter().filter(cs);
// TODO Auto-generated method stub
String text = inputSearch.getText().toString().toLowerCase(Locale.getDefault());
adapter.filter(text);
}
#Override
public void beforeTextChanged(CharSequence arg0, int arg1, int arg2,
int arg3) {
// TODO Auto-generated method stub
}
#Override
public void afterTextChanged(Editable arg0) {
// TODO Auto-generated method stub
}
});
}
#Override
public void onDestroy() {
super.onDestroy();
hidePDialog();
}
private void hidePDialog() {
if (pDialog != null) {
pDialog.dismiss();
pDialog = null;
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
}
**
Activity 2:
**
package activity;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import android.widget.ImageView;
import android.widget.TextView;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.VolleyLog;
import com.android.volley.toolbox.JsonArrayRequest;
import com.android.volley.toolbox.NetworkImageView;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.List;
import adapter.CustomListAdapter;
import model.Movie;
import puerile.toystore.com.R;
/**
* Created by on 12/3/15.
*/
public class ProductDetailInformation extends Activity {
private static final String TAG = ProductDetailInformation.class.getSimpleName();
// Movies json url
// private static final String url = "http://*.*.*.*:0000/android_login_api/toys.json"; //home
private static final String url = "http://*.*.*.*:0000/android_login_api/toys.json"; //starbucks
private ProgressDialog pDialog;
TextView title;
TextView description;
TextView price;
TextView rating;
NetworkImageView image;
TextView id;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.list_item);
pDialog = new ProgressDialog(this);
// Showing progress dialog before making http request
pDialog.setMessage("Loading...");
pDialog.show();
title = (TextView) findViewById(R.id.title);
price = (TextView) findViewById(R.id.price);
rating = (TextView) findViewById(R.id.rating);
description = (TextView) findViewById(R.id.description);
image = (NetworkImageView) findViewById(R.id.thumbnail);
Intent intent = getIntent();
// String headerInfo = intent.getExtras().getString("name");
// String priceInfo = intent.getExtras().getString("price");
//// String addtocartInfo = intent.getExtras().getString("addtocart");
// Bundle userdata = intent.getExtras();
// double result = userdata.getDouble("rating");
// String detailInfo = intent.getExtras().getString("description");
// // String ratingInfo = intent.getExtras().getString("rating");
// Bundle extras = getIntent().getExtras();
// byte[] b = extras.getByteArray("image");
// Bitmap bmp = BitmapFactory.decodeByteArray(b, 0, b.length);
// BitmapDrawable background = new BitmapDrawable(bmp);
String idInfo = intent.getExtras().getString("id");
// title.setText(headerInfo);
// price.setText(priceInfo);
//// title.setText(addtocartInfo);
// String stringdouble = Double.toString(result);
// rating.setText(stringdouble);
// description.setText(detailInfo);
// image.setBackground(background);
id.setText(idInfo);
hidePDialog();
}
#Override
public void onDestroy() {
super.onDestroy();
hidePDialog();
}
private void hidePDialog() {
if (pDialog != null) {
pDialog.dismiss();
pDialog = null;
}
}
}
You will need a proper endpoint to get the toy details. Normally passing the id as a REST path (android_login_api/toys/) or in the query string (android_login_api/toys?id=), there are multiple options.
If you have only the endpoint with the list of toys, instead of passing only the id to the Activity2, you can also use the intent to send the json section of the toy which user have been selected, as a string. So, Activity2 will receive the json data in the intent data.
Anyway, I extremely recommend you to use a serialisation library, such as GSON or Jackson, to convert JSON into Java classes. It is easy to create a model from JSON objects and configure Volley to return the required model Java class (or list) when you send a Volley request.
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.
I am getting some compile time error while extend to
BaseFragment.If I extend my VideoDetailFragment.java to Activity I doesn't get any
errors.
But I need to extend it to BaseFragment.Because I need to get the
ListViewwhile clicking that I can get the video displayed in that
url.
My issue is I am getting the Following Error:
The constructor ArrayAdapter(VideoDetailFragment, int, String[]) is undefined
The method finish() is undefined for the type VideoDetailFragment
The constructor Intent(VideoDetailFragment,
Class) is undefined
The constructor ProgressDialog(VideoDetailFragment) is undefined
Below I mentioned these all errors at the end of the Line.
VideoDetailFragment.java:
package com.sit.fth.frgment;
import android.content.Context;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.app.Activity;
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.ArrayAdapter;
import android.widget.ListView;
import android.app.ProgressDialog;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import com.fth.android.R;
import com.sit.fth.app.BaseFragment;
import com.sit.fth.model.JSONParser;
import com.sit.fth.activity.YoutubePlayActivity;
import java.util.ArrayList;
import java.util.List;
public class VideoDetailFragment extends BaseFragment {
// Categories must be pre-set
private String[] data = {"Category1", "Category2", "Category3"};
private final String TAG_VIDEOS = "videos";
private final String TAG_CAT = "video_category";
private final String TAG_URL = "video_url";
private final String TAG_TITLE = "video_title";
private List<String> videoTitles = new ArrayList<String>();
private List<String> videoURLs = new ArrayList<String>();
private ArrayAdapter<String> adapter;
private Object extras;
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.list1, null);
ListView listView = ((ListView)view.findViewById(R.id.listview));
AdapterView.OnItemClickListener clickListener = null;
// Category view:
if (extras == null) {
clickListener = new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
Intent intent = new Intent(VideoDetailFragment.this,VideoDetailFragment.class); ----->3rd Error
intent.putExtra("categoryName", data[position]);
startActivity(intent);
}
};
adapter = new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1, data); --->1st Error at this line
}
else { // Child view
// Get the category of this child
String categoryName = ((Bundle) extras).getString("categoryName");
if (categoryName == null)
finish(); ------>2nd Error
// Populate list with videos of "categoryName", by looping JSON data
new JSONParse(categoryName).execute();
clickListener = new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
Intent intent = new Intent(VideoDetailFragment.this, YoutubePlayActivity.class); ----->Third Error
// Send video url and title to YoutubeActivity
intent.putExtra("videoUrl", videoURLs.get(position));
intent.putExtra("videoTitle", videoTitles.get(position));
startActivity(intent);
}
};
adapter = new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1, videoTitles); ---->First Error
}
listView.setAdapter(adapter);
listView.setTextFilterEnabled(true);
listView.setOnItemClickListener(clickListener);
return listView;
}
private class JSONParse extends AsyncTask<String, String, JSONObject> {
private ProgressDialog pDialog;
private String categoryName;
// Constructor // Get the categoryName of which videos will be found
public JSONParse(String category) {
this.categoryName = category;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
// Create a loading dialog when getting the videos
pDialog = new ProgressDialog(VideoDetailFragment.this); ---->4th Error
pDialog.setMessage("Getting Videos...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
#Override
protected JSONObject doInBackground(String... args) {
JSONParser jParser = new JSONParser();
// Get JSON from URL
JSONObject json = jParser.getJSONFromUrl(JSONUrl);
if (json == null)
return null;
try {
// Get video array
JSONArray videos = json.getJSONArray(TAG_VIDEOS);
// Loop all videos
for (int i=0; i<videos.length(); i++) {
JSONObject video = videos.getJSONObject(i);
Log.e("JSON:", "cat: "+video.getString(TAG_CAT)+",title: "+video.getString(TAG_TITLE)+", url: "+video.getString(TAG_URL));
// Check if video belongs to "categoryName"
if (video.getString(TAG_CAT).equals(categoryName)) {
addVideo(video);
}
}
} catch (JSONException e) {
e.printStackTrace();
}
return json;
}
private void addVideo(JSONObject video) {
try {
// Add title and URL to their respective arrays
videoTitles.add(video.getString(TAG_TITLE));
videoURLs.add(video.getString(TAG_URL));
} catch (JSONException e) {
e.printStackTrace();
}
}
#Override
protected void onPostExecute(JSONObject json) {
// Close the "loading" dialog
pDialog.dismiss();
if (json == null) {
// Do something when there's no internet connection
// Or there are no videos to be displayed
}
else // Let the adapter notify ListView that it has new items
adapter.notifyDataSetChanged();
}
}
}
I doesn't know how to solve these.Anybody can help me with these.thank you.
#stephen.
Did u try to look for the crash where u are getting.
Plz see the following references where i think ur error will get resolved
1) Error: The constructor MainActivity.ScreenSlidePagerAdapter(FragmentManager) is undefined
2) FragmentPagerAdapter troubles and woes: Constructor Undefined
3)Why am I getting a Constructor Undefined error?
Let me know if you find some more issue or any kind of help is needed.
Thanks
You need to provide a reference to a Context, not a Fragment. Instead of adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, videoTitles), you should be doing adapter = new ArrayAdapter<String>(getActivity(), android.R.layout.simple_list_item_1, videoTitles);, and similarly passing in getActivity() instead of this for all the other methods where you have erros.
Fragments are not context objects. You need to pass the Activity object by using getActivity() as first argument in array adapter.
Instead of passing this in this line ==> adapter = new
ArrayAdapter(this,
android.R.layout.simple_list_item_1, data);
pass getActivity() like this:
adapter = new ArrayAdapter(getActivity(),
android.R.layout.simple_list_item_1, data);