my error log
I tried to load list view in my fragment.But my app crashes on clicking the button to populate my listview. I don't know what error i did.Any help will be appreciated.I have tried most of the stuffs regarding this..But nothing works well.(i have removed some codes to avoid clumsy look)
Here is my Fragment code :
public class Func extends Fragment {
ArrayList<Flowers> flowersList = new ArrayList<Flowers>();
String url ="http://113.193.30.155/MobileService/MobileService.asmx/GetSampleData";
#Override
public android.view.View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.tab2, container, false);
FlowerAdapter adapter=new FlowerAdapter(getActivity().getApplicationContext(),R.layout.flower_list_xml,flowersList);
ListView listView=(ListView)rootView.findViewById(R.id.listView);
listView.setAdapter(adapter);
return rootView;
}
#Override
public void onViewCreated(View view, #Nullable Bundle savedInstanceState) {
Button b = (Button)getView().findViewById(R.id.button);
b.setOnClickListener( new View.OnClickListener() {
#Override
public void onClick(View view) {
new BackTask().execute(url);
}
});
}
// My Async task starts here
public class BackTask extends AsyncTask<String, Void, String> {
#Override
protected void onPreExecute(){
super.onPreExecute();
}
#Override
protected String doInBackground(String... strings) {
String result = null;
BufferedReader reader = null;
try {
URL url = new URL(strings[0]);
HttpURLConnection con = (HttpURLConnection) url.openConnection();
StringBuilder sb = new StringBuilder();
reader = new BufferedReader(new InputStreamReader(con.getInputStream()));
Log.d("testhtt2", "test");
String line;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
Log.d("test44", sb.toString());
return sb.toString();
} catch (Exception e) {
e.printStackTrace();
return null;
} finally {
if (reader != null) {
try {
reader.close();
} catch (IOException e) {
e.printStackTrace();
return null;
}
}
return result;
}
}
#Override
protected void onPostExecute(String s){
try {
JSONArray ar =new JSONArray(s);
for (int i = 0; i < ar.length(); i++){
JSONObject jsonObject=ar.getJSONObject(i);
Flowers flowers= new Flowers();
flowers.setName(jsonObject.getString("NAME"));
flowersList.add(flowers);
}
} catch (JSONException e) {
e.printStackTrace();
}
You return null in your doInBackground, which you then attempt to parse as a JSONArray in your OnPostExecute. Return a proper String from your doInBackground method, and see if that helps.
Do a null check before using getView() like
if(getView()!=null){
//Your code
}
Also it is better to initialize the button in oncreate view using the rootview intead of getview()
EDIT:
Your network call which your are doing has to be moved to doInBackground as it should be done in background thread and fetch the result.The fetched result should be added to the list in onPostExecute.Hope this helps you
public class SampleClass extends AsyncTask<String, Void, String> {
#Override
protected void onPreExecute(){
super.onPreExecute();
}
#Override
protected String doInBackground(String... strings) {
BufferedReader reader = null;
String result=null;
try {
URL url = new URL(strings[0]);
HttpURLConnection con = (HttpURLConnection) url.openConnection();
StringBuilder sb = new StringBuilder();
reader = new BufferedReader(new InputStreamReader(con.getInputStream()));
Log.d("testhtt2", "test");
String line;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
Log.d("test44", sb.toString());
result= sb.toString();
} catch (Exception e) {
e.printStackTrace();
result= null;
} finally {
if (reader != null) {
try {
reader.close();
} catch (IOException e) {
e.printStackTrace();
result= null;
}
}
return result;
}
}
#Override
protected void onPostExecute(String s){
try {
JSONArray ar =new JSONArray(s);
for (int i = 0; i < ar.length(); i++){
JSONObject jsonObject=ar.getJSONObject(i);
Flowers flowers= new Flowers();
flowers.setName(jsonObject.getString("NAME"));
flowersList.add(flowers);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}
you can try with view insteadof getView() in onViewCreated() method.
public class ListView extends Fragment {
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.tab2, container, false);
return rootView;
}
#Override
public void onViewCreated(View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
Button b = (Button) view.findViewById(R.id.button);
b.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
new BackTask().execute("http://113.193.30.155/MobileService/MobileService.asmx/GetSampleData");
}
});
}
private class BackTask extends AsyncTask<String, Void, String> {
String result;
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected String doInBackground(String... params) {
try {
result = Utility.executeHttpGet(params[0]);
} catch (Exception e) {
Log.e("ListView", e.getMessage(), e);
}
return result;
}
#Override
protected void onPostExecute(String s) {
try {
JSONArray ar = new JSONArray(s);
for (int i = 0; i < ar.length(); i++) {
JSONObject jsonObject = ar.getJSONObject(i);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}
}
Try this code
public class Listview extends Fragment {
ArrayList<Flowers> flowersList = new ArrayList<Flowers>();
String url ="http://113.193.30.155/MobileService/MobileService.asmx/GetSampleData";
ListView listview;
View rootView;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
if (rootView!= null) {
ViewGroup parent = (ViewGroup) view.getParent();
if (parent != null)
parent.removeView(view);
}
try {
rootView = inflater.inflate(R.layout.tab2, container, false);
} catch (InflateException ignored) {
}
listView=(ListView)rootView.findViewById(R.id.listView);
Button b = (Button)rootView.findViewById(R.id.button);
b.setOnClickListener( new View.OnClickListener() {
#Override
public void onClick(View view) {
new BackTask().execute(url);
}
});
return view;
}
private class BackTask extends AsyncTask<String,String,String>{
#Override
protected void onPreExecute(){
super.onPreExecute();
}
#Override
protected String doInBackground(String... strings) {
return null;
}
#Override
protected void onPostExecute(String s){
try {
JSONArray ar =new JSONArray(s);
for (int i = 0; i < ar.length(); i++){
JSONObject jsonObject=ar.getJSONObject(i);
Flowers flowers= new Flowers();
flowers.setName(jsonObject.getString("NAME"));
flowersList.add(flowers);
}
FlowerAdapter adapter=new FlowerAdapter(getActivity(),R.layout.flower_list_xml,flowersList);
listView.setAdapter(adapter);
} catch (JSONException e) {
e.printStackTrace();
}
}
}
}
}
Related
I am trying to code a recipe app, I am pulling the recipes from an online JSON file.
Therefore I needed a custom ArrayAdapter and now I want to filter the List.
But as it turns out the adapter can't get the Filter function. I looked up other articles but none of them were helpful. Hope somebody can help out in this case.
This is the tutorial I watched to code online JSON to ListView: https://www.youtube.com/watch?v=v4X0y6-VOtM
Here is my Code:
public class Food_choosing_menu extends Fragment {
private ListView lv;
SearchView searchView;
ListAdapter adapter;
String name,time;
private static String JSON_URL = "https://---.github.io/---.json";
ArrayList<HashMap<String, String>> recepieList;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.fragment_food_choosing_menu, container, false);
recepieList = new ArrayList<>();
lv = v.findViewById(R.id.Food_List_View);
searchView = v.findViewById(R.id.Searh_bar_food);
GetData getData = new GetData();
getData.execute();
return v;
}
public class GetData extends AsyncTask<String, String, String>{
#Override
protected String doInBackground(String... strings) {
String current = "";
try {
URL url;
HttpURLConnection urlConnection = null;
try {
url = new URL(JSON_URL);
urlConnection = (HttpURLConnection) url.openConnection();
InputStream inputStream = urlConnection.getInputStream();
InputStreamReader inputStreamReader = new InputStreamReader(inputStream);
int data = inputStreamReader.read();
while (data != -1) {
current += (char) data;
data = inputStreamReader.read();
}
return current;
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (urlConnection != null) {
urlConnection.disconnect();
}
}
}catch (Exception e){
e.printStackTrace();
}
return current;
}
#Override
protected void onPostExecute(String s) {
try {
JSONObject jsonObject = new JSONObject(s);
JSONArray jsonArray = jsonObject.getJSONArray("Recepies");
for (int i = 0; i< jsonArray.length(); i++){
JSONObject jsonObject1 = jsonArray.getJSONObject(i);
name = jsonObject1.getString("name");
time = jsonObject1.getString("time");
HashMap<String, String> recepies = new HashMap<>();
recepies.put("name", name);
recepies.put("time", time);
recepieList.add(recepies);
}
}catch (JSONException e){
e.printStackTrace();
}
adapter = new SimpleAdapter(
getContext(),
recepieList,
R.layout.row_layout,
new String[] {"name", "time"},
new int[]{R.id.textView1});
lv.setAdapter(adapter);
lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Toast.makeText(getContext(), "You Click -"+adapter.getItem(position).toString(), Toast.LENGTH_SHORT).show();
}
});
searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
#Override
public boolean onQueryTextSubmit(String query) {
return false;
}
#Override
public boolean onQueryTextChange(String newText) {
return false;
}
});
}
}
i am trying to send Data (ID value) from one activity to other
but it wouldn't send correct data , i want it to send only ID Value of Clicked Item to next activity , here is my code
public class Order extends AppCompatActivity {
private ListView lvUsers;
private ProgressDialog dialog;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_sub);
dialog = new ProgressDialog(this);
dialog.setIndeterminate(true);
dialog.setCancelable(false);
dialog.setMessage("Loading, please wait.....");
lvUsers = (ListView) findViewById(R.id.lvUsers);
new JSONTask().execute("http://146.185.178.83/resttest/order");
}
public class JSONTask extends AsyncTask<String, String, List<OrderModel> > {
#Override
protected void onPreExecute(){
super.onPreExecute();
dialog.show();
}
#Override
protected List<OrderModel> doInBackground(String... params) {
HttpURLConnection connection = null;
BufferedReader reader = null;
try {
URL url = new URL(params[0]);
connection = (HttpURLConnection) url.openConnection();
connection.connect();
InputStream stream = connection.getInputStream();
reader = new BufferedReader(new InputStreamReader(stream));
StringBuffer buffer = new StringBuffer();
String line ="";
while ((line=reader.readLine()) !=null){
buffer.append(line);
}
String finalJson = buffer.toString();
JSONArray parentArray = new JSONArray(finalJson);
List<OrderModel> orderModelList = new ArrayList<>();
Gson gson = new Gson();
for (int i = 0; i < parentArray.length(); i++) {
JSONObject finalObject = parentArray.getJSONObject(i);
OrderModel orderModel = gson.fromJson(finalObject.toString(), OrderModel.class);
orderModelList.add(orderModel);
}
return orderModelList;
}catch (MalformedURLException e) {
e.printStackTrace();
}catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
} finally {
if(connection !=null) {
connection.disconnect();
}
try {
if (reader !=null) {
reader.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
return null;
}
#Override
protected void onPostExecute(List<OrderModel> result) {
super.onPostExecute(result);
dialog.dismiss();
OrderAdapter adapter = new OrderAdapter(getApplicationContext(), R.layout.row_order, result);
lvUsers.setAdapter(adapter);
}
}
public class OrderAdapter extends ArrayAdapter {
public List<OrderModel> orderModelList;
private int resource;
private LayoutInflater inflater;
public OrderAdapter(Context context, int resource, List<OrderModel> objects) {
super(context, resource, objects);
orderModelList = objects;
this.resource = resource;
inflater = (LayoutInflater) getSystemService(LAYOUT_INFLATER_SERVICE);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder = null;
if(convertView == null){
holder = new ViewHolder();
convertView=inflater.inflate(resource, null);
holder.bOrderNo = (Button) convertView.findViewById(R.id.bOrderNo);
convertView.setTag(holder);
}else {
holder = (ViewHolder) convertView.getTag();
}
final int orderId = orderModelList.get(position).getId();
holder.bOrderNo.setText("Order No: " + orderModelList.get(position).getOrderId());
holder.bOrderNo.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(Order.this, OrderSelected.class);
intent.putExtra("parameter_name", orderId);
startActivity(intent);
}
});
return convertView;
}
class ViewHolder{
private Button bOrderNo;
}
}
}
The holder gets executed in loop i guess is why it wouldn't send right Id.
How do i get it to send only Id of the clicked orderId
you can check this link to see how json Response looks like http://146.185.178.83/resttest/order
You have a silly mistake in your code . I have edited single line in your code . I think you are getting same "orderId" every time instead of actual "orderId". Check this one . I hope your problem will resolve .
final int index = position;
holder.bOrderNo.setText("Order No: " + orderModelList.get(position).getOrderId());
holder.bOrderNo.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(Order.this, OrderSelected.class);
intent.putExtra("parameter_name", orderModelList.get(index).getId());
startActivity(intent);
}
});
Please try
In place of
intent.putExtra("parameter_name", orderId);
Please put
intent.putExtra("parameter_name", orderModelList.get(position).getId());
The problem is that whenever the user go to the third fragment then coming back to the first one, all the data in the first fragment will be gone.
the Data will parsed from a web service, using AsyncTask within the fragment
this my onCreate() method
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
mParam1 = getArguments().getString(ARG_PARAM1);
mParam2 = getArguments().getString(ARG_PARAM2);
}
int radius = 4;
double latitude = 51.3674718208489;
double longtitude = -0.119329656538836;
Boolean loyal = false;
int mer = 1;
try {
parameters.put(ConstantKeys.SEARCH_NAME, searchname);
parameters.put(ConstantKeys.LOYALTY, isLoyalty);
Log.d(CommunityFragment.class.getSimpleName(), parameters.toString());
} catch (JSONException e) {
e.printStackTrace();
}
FindOfferField();
}
this is my onCreateView() method
public View onCreateView(LayoutInflater inflater,
ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.community_fragment, container, false);
return rootView;
}
and this is my AsynTask()
public void FindOfferField() {
RegisterRequest request = new RegisterRequest(getActivity());
SharedPreferences userpass = getActivity().getSharedPreferences("USERPASS", 0);
String email = userpass.getString("username", null);
String password = userpass.getString("password", null);
Log.d(CommunityFragment.class.getSimpleName(), "Email:" + email + " Password:" + password);
request.getToken(email, password, new ApiRequestListener() {
#Override
public void onSuccess(Object object) {
(new FindOfferTask() {
#Override
protected void onPostExecute(JSONObject data) {
super.onPostExecute(data);
try {
if (data.getString(ConstantKeys.RESULT).equals("OK")) {
array = data.getJSONArray(ConstantKeys.RESULTS);
RowItem items;
rowItem = new ArrayList<RowItem>();
for (int i = 0; i < array.length(); i++) {
final JSONObject list = array.getJSONObject(i);
items = new RowItem();
int id = Integer.parseInt(offerList.getString("Id"));
byID = id;
Log.d("AnotherID", String.valueOf(byID));
Boolean isCommunity = offerList.getBoolean(ConstantKeys.IS_COMMUNITY);
items.setId(list.getInt("Id"));
items.setMerchantid(list.getInt(ConstantKeys.MERCHANTID));
items.setDescription(list.getString(ConstantKeys.DESCRIPTION));
items.setDateEnd(list.getString(ConstantKeys.DATE).replace("T00:00:00", ""));
items.setTokensFor(list.getString(ConstantKeys.FOR));
if (!offerList.isNull("ImageId")) {
int bitmapImageID = offerList.getInt("ImageId");
Log.d("BITMAPHAHA", String.valueOf(bitmapImageID));
items.setImageId(bitmapImageID);
}
rowItem.add(items);
listView = (ListView) getView().findViewById(R.id.listViewCommunity);
adapter = new CustomListAdapter(getActivity(), rowItem);
adapter.notifyDataSetChanged();
listView.setAdapter(adapter);
getEndTask = new RowItemLoyalty();
getTask = new RowItem();
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
boolean isCommunity = false;
try {
isCommunity = offerList.getBoolean(ConstantKeys.IS_COMMUNITY);
} catch (JSONException e) {
e.printStackTrace();
}
int ID = rowItem.get(position).getId();
int merID = rowItem.get(position).getMerchantid();
Intent intent = new Intent(getActivity(), CustomerPromotion.class);
getEndTask.endTask();
getTask.endTask();
intent.putExtra("ID", ID);
intent.putExtra("MERCHANT", merID);
intent.putExtra("BOOLEANVALUE", isCommunity);
startActivity(intent);
}
});
}
Log.d("JSON Data", data.toString());
}
} catch (JSONException e) {
e.printStackTrace();
}
Log.d("JSON DATA", data.toString());
Log.w("Success Register", data.toString());
}
}).execute();
}
#Override
public void onError(String error) {
Log.e("Registration Error", error);
}
});
}
UPDATE
public class CommunityFragment extends ListFragment{
//LocationListener location;
ProgressDialog progressDialog;
Context context;
public static JSONObject parameters = new JSONObject();
private static final String STATE_LIST = "State Adapter Data";
public static final String DATA = "DATA";
public CustomerAccount customerAccount;
//---------Find Parameters----------
int byID;
//CustomListAdapter adapter;
public static String TAG = CommunityFragment.class.getSimpleName();
ListView listView;
ArrayList<RowItem> rowItem;
View view;
private static final String ARG_PARAM1 = "param1";
private static final String ARG_PARAM2 = "param2";
String searchname = ConstantSearch.SEARCHNAME;
CustomListAdapter adapter;
private String mParam1;
private String mParam2;
RowItemLoyalty getEndTask;
RowItem getTask;
RowItem storeData;
int index;
int top;
JSONArray array;
public CommunityFragment() {
}
public static CommunityFragment newInstance(String param1, String param2) {
CommunityFragment fragment = new CommunityFragment();
Bundle args = new Bundle();
args.putString(ARG_PARAM1, param1);
args.putString(ARG_PARAM2, param2);
fragment.setArguments(args);
return fragment;
}
#Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
String dataInJson = new Gson().toJson(rowItem);
outState.putString(DATA, dataInJson);
super.onSaveInstanceState(outState);
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
if(savedInstanceState != null && savedInstanceState.containsKey(DATA))
{
Log.d("StringData", DATA);
String jsonData = savedInstanceState.getString(DATA);
rowItem = new Gson().fromJson(jsonData, new TypeToken<List<RowItem>>(){}.getType());
}
else
{
rowItem = new ArrayList<>();
}
adapter = new CustomListAdapter(getActivity(), rowItem);
listView.setAdapter(adapter);
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
mParam1 = getArguments().getString(ARG_PARAM1);
mParam2 = getArguments().getString(ARG_PARAM2);
}
int radius = 4;
double latitude = 51.3674718208489;
double longtitude = -0.119329656538836;
Boolean isLoyalty = false;
int mer = 1;
try {
parameters.put(ConstantKeys.SEARCH_NAME, searchname);
parameters.put(ConstantKeys.LOYALTY, isLoyalty);
Log.d(CommunityFragment.class.getSimpleName(), parameters.toString());
} catch (JSONException e) {
e.printStackTrace();
}
FindOfferField();
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.community_fragment, container, false);
rowItem = new ArrayList<RowItem>();
listView = (ListView) rootView.findViewById(R.id.listViewCommunity);
return rootView;
}
public interface OnFragmentInteractionListener {
void onFragmentInteraction(Uri uri);
}
public void FindOfferField() {
RegisterRequest request = new RegisterRequest(getActivity());
SharedPreferences userpass = getActivity().getSharedPreferences("USERPASS", 0);
String email = userpass.getString("username", null);
String password = userpass.getString("password", null);
Log.d(CommunityFragment.class.getSimpleName(), "Email:" + email + " Password:" + password);
request.getToken(email, password, new ApiRequestListener() {
#Override
public void onSuccess(Object object) {
(new FindOfferTask() {
#Override
protected void onPostExecute(JSONObject data) {
super.onPostExecute(data);
try {
if (data.getString(ConstantKeys.RESULT).equals("OK")) {
array = data.getJSONArray(ConstantKeys.RESULTS);
RowItem items;
rowItem = new ArrayList<RowItem>();
for (int i = 0; i < array.length(); i++) {
final JSONObject offerList = array.getJSONObject(i);
items = new RowItem();
int id = Integer.parseInt(offerList.getString("Id"));
byID = id;
Log.d("AnotherID", String.valueOf(byID));
Boolean isCommunity = offerList.getBoolean(ConstantKeys.IS_COMMUNITY);
items.setId(offerList.getInt("Id"));
items.setMerchantid(offerList.getInt(ConstantKeys.FAVORITE_MERCHANTID));
items.setDescription(offerList.getString(ConstantKeys.DESCRIPTION));
items.setDateEnd(offerList.getString(ConstantKeys.DATE_END).replace("T00:00:00", ""));
items.setTokensFor(offerList.getString(ConstantKeys.TOKENSFOR));
if (!offerList.isNull("ImageId")) {
int bitmapImageID = offerList.getInt("ImageId");
Log.d("BITMAPHAHA", String.valueOf(bitmapImageID));
items.setImageId(bitmapImageID);
}
rowItem.add(items);
adapter = new CustomListAdapter(getActivity(), rowItem);
listView.setAdapter(adapter);
adapter.notifyDataSetChanged();
getEndTask = new RowItemLoyalty();
getTask = new RowItem();
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
boolean isCommunity = false;
try {
isCommunity = offerList.getBoolean(ConstantKeys.IS_COMMUNITY);
} catch (JSONException e) {
e.printStackTrace();
}
int offerID = rowItem.get(position).getId();
int merID = rowItem.get(position).getMerchantid();
Intent intent = new Intent(getActivity(), CustomerPromotion.class);
getEndTask.endTask();
getTask.endTask();
intent.putExtra("ID", offerID);
intent.putExtra("MERCHANT", merID);
intent.putExtra("BOOLEANVALUE", isCommunity);
startActivity(intent);
}
});
}
Log.d("JSON Data", data.toString());
}
} catch (JSONException e) {
e.printStackTrace();
}
Log.d("JSON DATA", data.toString());
Log.w("Success Register", data.toString());
}
}).execute();
}
#Override
public void onError(String error) {
Log.e("Registration Error", error);
}
});
}
public class FindOfferTask extends AsyncTask<Void, Void, JSONObject> {
#Override
protected void onPreExecute() {
super.onPreExecute();
progressDialog = new ProgressDialog(getActivity());
progressDialog.setMessage("Loading...");
progressDialog.setCancelable(false);
progressDialog.show();
}
#Override
protected JSONObject doInBackground(Void... params) {
ApiSecurityManager manager = ApiSecurityManager.getInstance();
String result = manager.apiCall("Offers/find", parameters.toString(), "C");
Log.d(CommunityFragment.class.getSimpleName(), result);
JSONObject jsonResult = new JSONObject();
Log.i(getClass().getSimpleName(), result);
try
{
jsonResult = new JSONObject(result);
}
catch (JSONException e)
{
e.printStackTrace();
}
return jsonResult;
}
protected void onPostExecute(JSONObject jsonObject) {
//loadingMore = false;
progressDialog.dismiss();
}
}
}
First of all, keep your view creation outside ApiRequestListener. Initialize all views in onCreateView() only.
// Key for storing data in `savedInstance`
public static final String DATA = "DATA";
In onCreateView()
public View onCreateView(LayoutInflater inflater,
ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.community_fragment, container, false);
rowItem = new ArrayList<RowItem>();
listView = (ListView) rootView.findViewById(R.id.listViewCommunity);
return rootView;
}
When activity is created, check if data is available in savedInstanceState or not and based on that start web service.
#Override
public void onActivityCreated(Bundle savedInstanceState)
{
super.onActivityCreated(savedInstanceState);
if(savedInstanceState.containsKey(DATA))
{
String jsonData = savedInstanceState.getString(DATA);
rowItem = new Gson().fromJson(jsonData, new TypeToken<List<RowItem>>(){}.getType());
}
else
{
rowItem = new ArrayList<>();
}
adapter = new CustomListAdapter(getActivity(), rowItem);
listView.setAdapter(adapter);
// Now here, check the size of array list. If it is 0, then start service to fetch data from server
}
To convert your list into string, I am using Gson library here.
#Override
public void onSaveInstanceState(Bundle outState)
{
// Here use gson library from google to convert list of data to string.
String dataInJson = new Gson().toJson(rowItem);
outState.putString(DATA, dataInJson);
super.onSaveInstanceState(outState);
}
And your method will look like this:
public void FindOfferField() {
RegisterRequest request = new RegisterRequest(getActivity());
SharedPreferences userpass = getActivity().getSharedPreferences("USERPASS", 0);
String email = userpass.getString("username", null);
String password = userpass.getString("password", null);
Log.d(CommunityFragment.class.getSimpleName(), "Email:" + email + " Password:" + password);
request.getToken(email, password, new ApiRequestListener() {
#Override
public void onSuccess(Object object) {
(new FindOfferTask() {
#Override
protected void onPostExecute(JSONObject data) {
super.onPostExecute(data);
try {
if (data.getString(ConstantKeys.RESULT).equals("OK")) {
array = data.getJSONArray(ConstantKeys.RESULTS);
RowItem items;
for (int i = 0; i < array.length(); i++) {
final JSONObject list = array.getJSONObject(i);
items = new RowItem();
int id = Integer.parseInt(offerList.getString("Id"));
byID = id;
Log.d("AnotherID", String.valueOf(byID));
Boolean isCommunity = offerList.getBoolean(ConstantKeys.IS_COMMUNITY);
items.setId(list.getInt("Id"));
items.setMerchantid(list.getInt(ConstantKeys.MERCHANTID));
items.setDescription(list.getString(ConstantKeys.DESCRIPTION));
items.setDateEnd(list.getString(ConstantKeys.DATE).replace("T00:00:00", ""));
items.setTokensFor(list.getString(ConstantKeys.FOR));
if (!offerList.isNull("ImageId")) {
int bitmapImageID = offerList.getInt("ImageId");
Log.d("BITMAPHAHA", String.valueOf(bitmapImageID));
items.setImageId(bitmapImageID);
}
rowItem.add(items);
adapter.notifyDataSetChanged();
getEndTask = new RowItemLoyalty();
getTask = new RowItem();
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
boolean isCommunity = false;
try {
isCommunity = offerList.getBoolean(ConstantKeys.IS_COMMUNITY);
} catch (JSONException e) {
e.printStackTrace();
}
int ID = rowItem.get(position).getId();
int merID = rowItem.get(position).getMerchantid();
Intent intent = new Intent(getActivity(), CustomerPromotion.class);
getEndTask.endTask();
getTask.endTask();
intent.putExtra("ID", ID);
intent.putExtra("MERCHANT", merID);
intent.putExtra("BOOLEANVALUE", isCommunity);
startActivity(intent);
}
});
}
Log.d("JSON Data", data.toString());
}
} catch (JSONException e) {
e.printStackTrace();
}
Log.d("JSON DATA", data.toString());
Log.w("Success Register", data.toString());
}
}).execute();
}
#Override
public void onError(String error) {
Log.e("Registration Error", error);
}
});
}
Hope this helps.
I am trying to pass 2 String[] from doinbackground to fragment where i have RecyclerView. I also tried setter getter method but still no luck
Here is my Fragment
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view=inflater.inflate(R.layout.activity_friend_list,container,false);
recyclerView= (RecyclerView) view.findViewById(R.id.RecyclerViewForFriendList);
//WANTS TO REPLACE THESE TWO ARRAY WITH WHICH I AM GETTING IN DOINBACKGROUND
Name=getResources().getStringArray(R.array.left_Drawer_Menu);
Image=getResources().obtainTypedArray(R.array.user_image);
recyclerView.setHasFixedSize(true);
adapter=new RecyclerFriendListAdapter(getActivity(),Distance,Image,LastSeen,Name);
recyclerView.setAdapter(adapter);
layoutManager=new LinearLayoutManager(getActivity());
recyclerView.setLayoutManager(layoutManager);
return view;
}
Here is my AsyncTask Class
protected String[] doInBackground(String... params) {
try {
URL url=new URL(URL_Path);
connection= (HttpURLConnection) url.openConnection();
connection.connect();
InputStream inputStream=connection.getInputStream();
reader=new BufferedReader(new InputStreamReader(inputStream));
String line;
StringBuffer stringBuffer=new StringBuffer();
while ((line=reader.readLine())!=null){
stringBuffer.append(line);
}
String completeJSON=stringBuffer.toString();
JSONArray parentArray=new JSONArray(completeJSON);
String[] Name=new String[parentArray.length()];
String[] ImagePath=new String[parentArray.length()];
for (int i = 0; i <parentArray.length() ; i++) {
JSONObject childObject=parentArray.getJSONObject(i);
String Fname=childObject.getString("First_Name") ;
String Lname=childObject.getString("Last_Name") ;
Name[i]=Fname+" "+Lname;
ImagePath[i]=childObject.getString("Image");
Log.d(TAG,"String Arrays "+Name[i]+" "+ ImagePath[i]);
//GETTING ALL VALUES IN LOG SUCCESSFULLY
}
return Name;
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
} finally {
try {
connection.disconnect();
if (reader!=null) {
reader.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
return null;
}
#Override
protected void onPostExecute(String[] strings) {
super.onPostExecute(strings);
}
I am calling AsyncTask Execute Method in Toolbar of Parent Activity Of Fragment
UPDATE:
1) As #BryanDunlap Asked for onPostExecute (its just implemented,No code inside it) And How to return both arrays to get in Fragment
2) #IrisLouis suggested to implement interface that's how i did with setter and getter but i wasn't work
ublic class WrapperClass {
private String[] Name;
private String[] ImagePath;
public String[] getImagePath() {
return ImagePath;
}
public void setImagePath(String[] imagePath) {
ImagePath = imagePath;
}
public String[] getName() {
return Name;
}
public void setName(String[] name) {
Name = name;
}
How i set this in AsyncTask
Name[i]=Fname+" "+Lname;
ImagePath[i]=childObject.getString("Image");
Log.d(TAG,"String Arrays "+Name[i]+" "+ ImagePath[i]);
//LOG RETURNS VALUE OF BOTH ARRAYS
WrapperClass w=new WrapperClass();
w.setImagePath(ImagePath);
w.setImagePath(Name);
Getting in Fragment in onCreateView
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
....
....
....
WrapperClass wrapperClass=new WrapperClass();
String[] Name=wrapperClass.getName();
String[] ImagePath=wrapperClass.getImagePath();
Log.d(TAG,Name.toString()+" "+ ImagePath.toString())
//IT RETURNS NULLS
Solution for you, can test it.
In class Asynctask make a interface callback results :
public class PageLoader extends AsyncTask<String, Void, String[] results> {
private Context context;
private LoaderListener mLoaderListener;
public PageLoader(Context context, LoaderListener mLoaderListener) {
this.context = context;
this.mLoaderListener = mLoaderListener;
}
public interface LoaderListener {
void onLoadCompleted(String[] results);
void onLoadFailed();
void onPreparing();
}
#Override
protected void onPreExecute() {
mLoaderListener.onPreparing();
}
#Override
protected String[] doInBackground(String... params) {
try {
URL url=new URL(URL_Path);
connection= (HttpURLConnection) url.openConnection();
connection.connect();
InputStream inputStream=connection.getInputStream();
reader=new BufferedReader(new InputStreamReader(inputStream));
String line;
StringBuffer stringBuffer=new StringBuffer();
while ((line=reader.readLine())!=null){
stringBuffer.append(line);
}
String completeJSON=stringBuffer.toString();
JSONArray parentArray=new JSONArray(completeJSON);
String[] Name=new String[parentArray.length()];
String[] ImagePath=new String[parentArray.length()];
for (int i = 0; i <parentArray.length() ; i++) {
JSONObject childObject=parentArray.getJSONObject(i);
String Fname=childObject.getString("First_Name") ;
String Lname=childObject.getString("Last_Name") ;
Name[i]=Fname+" "+Lname;
ImagePath[i]=childObject.getString("Image");
Log.d(TAG,"String Arrays "+Name[i]+" "+ ImagePath[i]);
//GETTING ALL VALUES IN LOG SUCCESSFULLY
}
return Name;
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
} finally {
try {
connection.disconnect();
if (reader!=null) {
reader.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
return null;
}
#Override
protected void onPostExecute(String[] results) {
if (results!= null) {
mLoaderListener.onLoadCompleted(results);
} else {
mLoaderListener.onLoadFailed();
}
}
}
In Activity you execute Asynctask.
In Fragment you must implements LoaderListener and Override three function.
Ex : YourFragment extends Fragment implements LoaderListener
You can handle results callback in onLoadCompleted
Ex :
#Override
public void onLoadCompleted(String[] results){
//Do something with results
}
So I'm trying to make a simple application that makes stores group events in a MySQL database then retrieves them for people to join. In this fragment I list all the events by using a JSONParser class to query the database. I use an Async class to do the querying. The fragment will initially query the db on startup or whenever the user decides to limit the scope of the events by selecting something in a spinner or when the user pushes a refresh button. I have been getting messages like
Choreographer﹕ Skipped 95 frames! The application may be doing too much work on its main thread.
while running the program and I'm not sure why. I think it might be because I call the Async class too much, but I'm not sure.
public class mainActivityFragment extends Fragment {
final public String information = "information";
public Spinner specifySubject;
private ArrayList<String> list = new ArrayList<>();
private ArrayList<EventObject> eventList = new ArrayList<>();
JSONParser jsonParser = new JSONParser();
ListView test;
ArrayAdapter adapter;
// url to create new product
private static String url_get_event = "";
private ProgressDialog pDialog;
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.activity_main, container, false);
adapter = new ArrayAdapter(getActivity(),android.R.layout.simple_list_item_1, list);
test = (ListView) v.findViewById(R.id.listView);
new CreateNewProduct().execute();
if(pDialog.isShowing()){
pDialog.dismiss();
}
test.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapter, View view, int position, long id) {
Intent in = new Intent(getActivity(), AttendInformation.class);
EventObject clickedEvent = eventList.get(position);
String[] testInformation = {clickedEvent.getTo().toString(), clickedEvent.getLocation(), clickedEvent.getTitle(), clickedEvent.getDurationString(), clickedEvent.getDescription(), clickedEvent.getSubject()};
in.putExtra(information, testInformation);
startActivity(in);
}
});
Button createEventButton = (Button) v.findViewById(R.id.Button2);
createEventButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Intent in = new Intent(getActivity(), createEvent.class);
startActivity(in);
}
});
specifySubject = (Spinner) v.findViewById(R.id.spinner);
specifySubject.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
AsyncTask task;
task = new CreateNewProduct().execute();
try {
task.get(3000, TimeUnit.MILLISECONDS);
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
} catch (TimeoutException e) {
e.printStackTrace();
}
if (position == 0) {
} else {
String selectedSubj = getResources().getStringArray(R.array.class_array)[position];
for (int i = 0; i < eventList.size(); i++) {
if (!eventList.get(i).getSubject().equals(selectedSubj)) {
list.remove(list.indexOf(eventList.get(i).getTitle()));
eventList.remove(i);
i--;
}
}
adapter.notifyDataSetChanged();
}
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
Button refresh = (Button) v.findViewById(R.id.leftButton);
refresh.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
AsyncTask task;
task = new CreateNewProduct().execute();
try {
task.get(3000, TimeUnit.MILLISECONDS);
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
} catch (TimeoutException e) {
e.printStackTrace();
}
if (specifySubject.getSelectedItemPosition() == 0) {
} else {
String selectedSubj = getResources().getStringArray(R.array.class_array)[specifySubject.getSelectedItemPosition()];
for (int i = 0; i < eventList.size(); i++) {
if (!eventList.get(i).getSubject().equals(selectedSubj)) {
list.remove(list.indexOf(eventList.get(i).getTitle()));
eventList.remove(i);
i--;
}
}
adapter.notifyDataSetChanged();
}
}
});
return v;
}
class CreateNewProduct extends AsyncTask<String, String, String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(getActivity());
pDialog.setMessage("Getting Events...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
protected String doInBackground(String... args) {
JSONArray jsonArr = jsonParser.getJSONFromUrl(url_get_event);
for(int n = 0; n < jsonArr.length(); n++)
{
try {
JSONObject object = jsonArr.getJSONObject(n);
if(!list.contains(object.getString("title"))){
String[] time = object.getString("time").split(":");
time[1] = time[1].substring(0, 2);
EventObject tempEven = new EventObject(object.getString("title"), object.getString("location"), object.getString("description"), object.getString("subject"), 0, new TimeObject(Integer.parseInt(time[0]), Integer.parseInt(time[1])));
eventList.add(tempEven);
list.add(object.getString("title"));
}
} catch (JSONException e) {
e.printStackTrace();
}
}
return null;
}
protected void onPostExecute(String file_url) {
// dismiss the dialog once done
test.setAdapter(adapter);
pDialog.dismiss();
}
}
}