Hello all i have a search activity into my app that works good if i try to search an item by tiping a text keyword but if i try to search an item that also contain a number app crash. For example if i try to search the text "home" search works good but if i search "home 3" app crash. The error is : exception-illegal-character-in-query-at-index I want that the search works good also by typing a text or a text + number exc..
Thank you
IMPORTANT :
the search activity call an encoded url, "ADSEARCH_URL"
public static final String ADSEARCH_URL="https://gjeme.com/apps/menjehere/index.php?action=searchAd&categoryId=%s&adcity=%s&q=%s";
This is the search activity :
public class SearchActivity extends AppCompatActivity {
Toolbar toolbar;
ListView lsv;
String categoryId,keyword,city;
ProgressDialog progressBar;
List<CatAdd> catAddList;
CateAdDisplayAdapter adapter;
Typeface typeface;
#SuppressLint("NewApi") #Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.activty_search);
toolbar = (Toolbar) findViewById(R.id.toolbar);
if (toolbar != null) {
toolbar.setTitle("Browse Ads");
setSupportActionBar(toolbar);
getSupportActionBar().setHomeButtonEnabled(true);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
}
getActionBarTextView();
typeface = Typeface.createFromAsset(getAssets(), "fonts/GandhiSerif- Bold.otf");
TabLayout tabLayout = (TabLayout) findViewById(R.id.tab_layout);
ViewPager viewPager = (ViewPager) findViewById(R.id.pager);
lsv = (ListView)findViewById(R.id.listView1);
catAddList = new ArrayList<CatAdd>();
categoryId = getIntent().getExtras().getString("categoryId", "0");
keyword = getIntent().getExtras().getString("keyword","keyword");
city = getIntent().getExtras().getString("city","city");
new SearchList().execute();
lsv.setOnItemClickListener(new OnItemClickListener()
{
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
long arg3) {
Intent intent = new Intent(getApplicationContext(), BrowseAdsDetailActivity.class);
intent.putExtra("adId", String.valueOf(catAddList.get(arg2).getAddid()));
startActivity(intent);
}
});
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if(id==android.R.id.home)
{
onBackPressed();
}
return super.onOptionsItemSelected(item);
}
#Override
public void onBackPressed() {
// TODO Auto-generated method stub
super.onBackPressed();
}
private TextView getActionBarTextView() {
TextView titleTextView = null;
try {
Field f = toolbar.getClass().getDeclaredField("mTitleTextView");
f.setAccessible(true);
titleTextView = (TextView)f.get(toolbar);
titleTextView.setTypeface(typeface);
} catch (NoSuchFieldException e) {
} catch (IllegalAccessException e) {
}
return titleTextView;
}
class SearchList extends AsyncTask<Void, Void, Void>
{
String jsonStr = null;
CustomProgressDialog cd = new CustomProgressDialog();
#Override
protected void onPreExecute() {
super.onPreExecute();
cd.showdialog(SearchActivity.this, "Loading...");
}
#Override
protected Void doInBackground(Void... arg0) {
ServiceHandler sh = new ServiceHandler();
jsonStr = sh.makeServiceCall(String.format(Constants.ADSEARCH_URL,categoryId,city,keyword) , ServiceHandler.GET);
Log.d("Response: ", "> " + jsonStr);
if (jsonStr != null) {
try {
JSONObject jsonObj = new JSONObject(jsonStr);
JSONArray contacts = jsonObj.getJSONArray(Constants.TAG);
for (int i = contacts.length()-1; i > -1; i--) {
JSONObject c = contacts.getJSONObject(i);
String adId = c.getString(Constants.CAT_ADID);
String adTitle = c.getString(Constants.CAT_ADTITLE);
String adDes = c.getString(Constants.CAT_ADDES);
String adCreatedAt = c.getString("adCreatedAt");
String adcity= c.getString(Constants.CAT_CITY);
String adPrise= c.getString(Constants.CAT_PRICE);
JSONArray arrImages=c.getJSONArray("images");
ArrayList<String> imgArray=new ArrayList<String>();
for(int j=0;j<arrImages.length();j++)
{
JSONObject imgObj=arrImages.getJSONObject(j);
if(imgObj.has("imageName"))
{
imgArray.add(imgObj.getString("imageName"));
}
}
CatAdd v=new CatAdd();
v.setAddid(Integer.parseInt(adId));
v.setAdTitle(adTitle);
v.setAdDesc(adDes);
v.setAdCreatedAt(adCreatedAt);
v.setAdPrice(adPrise);
v.setImglist(imgArray);
v.setAdCity(adcity);
catAddList.add(v);
}
} 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);
cd.dismissdialog();
adapter = new CateAdDisplayAdapter(getApplicationContext(), catAddList);
lsv.setAdapter(adapter);
}
}
}
I think there isn't any problem with alpha-numeric characters here, but the SPACE is created one, while you are adding the text to URL.
Replace space(es) of searched keyword with %20 and hopefully you will find it fine.
Related
i am working on a ecommerce app and i have a list where list of items will be there. Just like product name, price, discounted value etc fetched from database.
i am using ListView to show products where every item have there seprate Menu_ID. Whenever i click on list item following code is run where i use putExtra to open speciefic menu_id item details.
public void onItemClick(AdapterView<?> arg0, View arg1, int position,
long arg3) {
// TODO Auto-generated method stub
// go to menu detail page
Intent iDetail = new Intent(ActivityMenuList.this, ActivityMenuDetail.class);
iDetail.putExtra("menu_id", Menu_ID.get(position));
startActivity(iDetail);
}
and new activity will be open with product detail where i display add to cart button whenever i click on add to cart button item display in cart activity.
code is like
public void inputDialog() {
// open database first
try {
dbhelper.openDataBase();
} catch (SQLException sqle) {
throw sqle;
}
AlertDialog.Builder alert = new AlertDialog.Builder(this);
alert.setTitle(R.string.order);
alert.setMessage(R.string.number_order);
alert.setCancelable(false);
final EditText edtQuantity = new EditText(this);
int maxLength = 3;
edtQuantity.setFilters(new InputFilter[]{new InputFilter.LengthFilter(maxLength)});
edtQuantity.setInputType(InputType.TYPE_CLASS_NUMBER);
alert.setView(edtQuantity);
alert.setPositiveButton("Add", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
String temp = edtQuantity.getText().toString();
int quantity = 0;
// when add button clicked add menu to order table in database
if (!temp.equalsIgnoreCase("")) {
quantity = Integer.parseInt(temp);
Toast.makeText(getApplicationContext(), "Success add product to cart", Toast.LENGTH_SHORT).show();
if (dbhelper.isDataExist(Menu_ID)) {
dbhelper.updateData(Menu_ID, quantity, (Menu_price * quantity));
} else {
dbhelper.addData(Menu_ID, Menu_name, quantity, (Menu_price * quantity));
}
checkoutButton.setEnabled(true);
checkoutButton.setBackgroundColor(R.color.ColorPrimaryDark);
checkoutButton.setTextColor(Color.WHITE);
} else {
dialog.cancel();
checkoutButton.setEnabled(false);
}
}
});
alert.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
// when cancel button clicked close dialog
dialog.cancel();
}
});
alert.show();
}
Now the question is
i want to display add to cart button in product list where i place my order directly from product list without opening product detail.
ListActivity is like
public class ActivityMenuList extends AppCompatActivity {
ListView listMenu;
ProgressBar prgLoading;
SwipeRefreshLayout swipeRefreshLayout = null;
EditText edtKeyword;
ImageButton btnSearch;
TextView txtAlert;
// declare static variable to store tax and currency symbol
public static double Tax;
public static String Currency;
private ActivityMenuDetail details;
// declare adapter object to create custom menu list
AdapterMenuList mla;
// create arraylist variables to store data from server
public static ArrayList<Long> Menu_ID = new ArrayList<Long>();
public static ArrayList<String> Menu_name = new ArrayList<String>();
public static ArrayList<Double> Menu_price = new ArrayList<Double>();
public static ArrayList<String> Menu_image = new ArrayList<String>();
public static ArrayList<Double> Discounted_Price = new ArrayList<Double>();
public static ArrayList<String> Discounted_Value = new ArrayList<String>();
public static ArrayList<Double> Our_Price = new ArrayList<Double>();
String MenuAPI;
String fullAPI;
String TaxCurrencyAPI;
int IOConnect = 0;
long Category_ID;
String Category_name;
String Keyword;
// create price format
DecimalFormat formatData = new DecimalFormat("#.##");
DecimalFormat formatData1 = new DecimalFormat("#.##");
DecimalFormat formatData2 = new DecimalFormat("#.##");
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_menu_list);
final Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
final android.support.v7.app.ActionBar actionBar = getSupportActionBar();
if (actionBar != null) {
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setTitle(R.string.title_menu);
}
swipeRefreshLayout = (SwipeRefreshLayout) findViewById(R.id.swipeRefreshLayout);
swipeRefreshLayout.setColorSchemeResources(R.color.orange, R.color.green, R.color.blue);
prgLoading = (ProgressBar) findViewById(R.id.prgLoading);
listMenu = (ListView) findViewById(R.id.listMenu);
edtKeyword = (EditText) findViewById(R.id.edtKeyword);
btnSearch = (ImageButton) findViewById(R.id.btnSearch);
txtAlert = (TextView) findViewById(R.id.txtAlert);
// menu API url
MenuAPI = Config.ADMIN_PANEL_URL+"/api/get-menu-data-by-category-id2.php"+"?accesskey="+Config.AccessKey+"&category_id=";
// tax and currency API url
TaxCurrencyAPI = Config.ADMIN_PANEL_URL+"/api/get-tax-and-currency.php"+"?accesskey="+Config.AccessKey;
// get category id and category name that sent from previous page
Intent iGet = getIntent();
Category_ID = iGet.getLongExtra("category_id",0);
Category_name = iGet.getStringExtra("category_name");
MenuAPI += Category_ID;
mla = new AdapterMenuList(ActivityMenuList.this);
// call asynctask class to request tax and currency data from server
new getTaxCurrency().execute();
// event listener to handle search button when clicked
btnSearch.setOnClickListener(new OnClickListener() {
public void onClick(View arg0) {
// TODO Auto-generated method stub
// get keyword and send it to server
try {
Keyword = URLEncoder.encode(edtKeyword.getText().toString(), "utf-8");
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
MenuAPI += "&keyword=" + Keyword;
IOConnect = 0;
listMenu.invalidateViews();
clearData();
new getDataTask().execute();
}
});
// event listener to handle list when clicked
listMenu.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> arg0, View arg1, int position,
long arg3) {
// TODO Auto-generated method stub
// go to menu detail page
Intent iDetail = new Intent(ActivityMenuList.this, ActivityMenuDetail.class);
iDetail.putExtra("menu_id", Menu_ID.get(position));
startActivity(iDetail);
}
});
// Using to refresh webpage when user swipes the screen
swipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
#Override
public void onRefresh() {
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
swipeRefreshLayout.setRefreshing(false);
IOConnect = 0;
listMenu.invalidateViews();
clearData();
new getDataTask().execute();
}
}, 3000);
}
});
listMenu.setOnScrollListener(new AbsListView.OnScrollListener() {
#Override
public void onScrollStateChanged(AbsListView view, int scrollState) {
}
#Override
public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
boolean enable = false;
if (listMenu != null && listMenu.getChildCount() > 0) {
boolean firstItemVisible = listMenu.getFirstVisiblePosition() == 0;
boolean topOfFirstItemVisible = listMenu.getChildAt(0).getTop() == 0;
enable = firstItemVisible && topOfFirstItemVisible;
}
swipeRefreshLayout.setEnabled(enable);
}
});
}
#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_category, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
switch (item.getItemId()) {
case R.id.cart:
// refresh action
Intent i = new Intent(ActivityMenuList.this, ActivityCart.class);
startActivity(i);
return true;
case R.id.refresh:
IOConnect = 0;
listMenu.invalidateViews();
clearData();
new getDataTask().execute();
return true;
case android.R.id.home:
// app icon in action bar clicked; go home
this.finish();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
// asynctask class to handle parsing json in background
public class getTaxCurrency extends AsyncTask<Void, Void, Void>{
// show progressbar first
getTaxCurrency(){
if(!prgLoading.isShown()){
prgLoading.setVisibility(View.VISIBLE);
txtAlert.setVisibility(View.GONE);
}
}
#Override
protected Void doInBackground(Void... arg0) {
// TODO Auto-generated method stub
// parse json data from server in background
parseJSONDataTax();
return null;
}
#Override
protected void onPostExecute(Void result) {
// TODO Auto-generated method stub
// when finish parsing, hide progressbar
prgLoading.setVisibility(View.GONE);
// if internet connection and data available request menu data from server
// otherwise, show alert text
if((Currency != null) && IOConnect == 0){
new getDataTask().execute();
}else{
txtAlert.setVisibility(View.VISIBLE);
}
}
}
// method to parse json data from server
public void parseJSONDataTax(){
try {
// request data from tax and currency API
HttpClient client = new DefaultHttpClient();
HttpConnectionParams.setConnectionTimeout(client.getParams(), 15000);
HttpConnectionParams.setSoTimeout(client.getParams(), 15000);
HttpUriRequest request = new HttpGet(TaxCurrencyAPI);
HttpResponse response = client.execute(request);
InputStream atomInputStream = response.getEntity().getContent();
BufferedReader in = new BufferedReader(new InputStreamReader(atomInputStream));
String line;
String str = "";
while ((line = in.readLine()) != null){
str += line;
}
// parse json data and store into tax and currency variables
JSONObject json = new JSONObject(str);
JSONArray data = json.getJSONArray("data"); // this is the "items: [ ] part
JSONObject object_tax = data.getJSONObject(0);
JSONObject tax = object_tax.getJSONObject("tax_n_currency");
Tax = Double.parseDouble(tax.getString("Value"));
JSONObject object_currency = data.getJSONObject(1);
JSONObject currency = object_currency.getJSONObject("tax_n_currency");
Currency = currency.getString("Value");
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
IOConnect = 1;
// TODO Auto-generated catch block
e.printStackTrace();
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
// clear arraylist variables before used
void clearData(){
Menu_ID.clear();
Menu_name.clear();
Menu_price.clear();
Menu_image.clear();
Discounted_Value.clear();
Discounted_Price.clear();
Our_Price.clear();
}
// asynctask class to handle parsing json in background
public class getDataTask extends AsyncTask<Void, Void, Void>{
// show progressbar first
getDataTask(){
if(!prgLoading.isShown()){
prgLoading.setVisibility(View.VISIBLE);
txtAlert.setVisibility(View.GONE);
}
}
#Override
protected Void doInBackground(Void... arg0) {
// TODO Auto-generated method stub
// parse json data from server in background
parseJSONData();
return null;
}
#Override
protected void onPostExecute(Void result) {
// TODO Auto-generated method stub
// when finish parsing, hide progressbar
prgLoading.setVisibility(View.GONE);
// if data available show data on list
// otherwise, show alert text
if(Menu_ID.size() > 0){
listMenu.setVisibility(View.VISIBLE);
listMenu.setAdapter(mla);
}else{
txtAlert.setVisibility(View.VISIBLE);
}
}
}
// method to parse json data from server
public void parseJSONData(){
clearData();
try {
// request data from menu API
HttpClient client = new DefaultHttpClient();
HttpConnectionParams.setConnectionTimeout(client.getParams(), 15000);
HttpConnectionParams.setSoTimeout(client.getParams(), 15000);
HttpUriRequest request = new HttpGet(MenuAPI);
HttpResponse response = client.execute(request);
InputStream atomInputStream = response.getEntity().getContent();
BufferedReader in = new BufferedReader(new InputStreamReader(atomInputStream));
String line;
String str = "";
while ((line = in.readLine()) != null){
str += line;
}
// parse json data and store into arraylist variables
JSONObject json = new JSONObject(str);
JSONArray data = json.getJSONArray("data"); // this is the "items: [ ] part
for (int i = 0; i < data.length(); i++) {
JSONObject object = data.getJSONObject(i);
JSONObject menu = object.getJSONObject("Menu");
Menu_ID.add(Long.parseLong(menu.getString("Menu_ID")));
Menu_name.add(menu.getString("Menu_name"));
Menu_price.add(Double.valueOf(formatData.format(menu.getDouble("Price"))));
Discounted_Price.add(Double.valueOf(formatData1.format(menu.getDouble("Discounted_Price"))));
Our_Price.add(Double.valueOf(formatData2.format(menu.getDouble("Our_Price"))));
Menu_image.add(menu.getString("Menu_image"));
Discounted_Value.add(menu.getString("Discounted_Value"));
}
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
#Override
protected void onDestroy() {
// TODO Auto-generated method stub
//mla.imageLoader.clearCache();
listMenu.setAdapter(null);
super.onDestroy();
}
#Override
public void onConfigurationChanged(final Configuration newConfig)
{
// Ignore orientation change to keep activity from restarting
super.onConfigurationChanged(newConfig);
}
#Override
public void onBackPressed() {
// TODO Auto-generated method stub
super.onBackPressed();
finish();
}
ListAdapter code
public class AdapterMenuList extends BaseAdapter {
private Activity activity;
private ActivityMenuDetail details;
public AdapterMenuList(Activity act) {
this.activity = act;
}
public AdapterMenuList(ActivityMenuDetail details) {
this.details = details;
}
public int getCount() {
return ActivityMenuList.Menu_ID.size();
}
public Object getItem(int position) {
return position;
}
public long getItemId(int position) {
return position;
}
public View getView(final int position, View convertView, ViewGroup parent) {
final ViewHolder holder;
if(convertView == null){
LayoutInflater inflater = (LayoutInflater) activity
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = inflater.inflate(R.layout.lsv_item_menu_list, null);
holder = new ViewHolder();
holder.txtText = (TextView) convertView.findViewById(R.id.txtText);
holder.txtSubText = (TextView) convertView.findViewById(R.id.txtSubText);
holder.imgThumb = (ImageView) convertView.findViewById(R.id.ImageCatList);
holder.discounted_Price = (TextView) convertView.findViewById(R.id.DiscPriceCatList);
holder.discounted_Value = (TextView) convertView.findViewById(R.id.DiscValueCatList);
holder.discounted_Price.setTextColor(Color.GRAY);
holder.discounted_Price.setPaintFlags(holder.discounted_Price.getPaintFlags() | Paint.STRIKE_THRU_TEXT_FLAG);
holder.addtocart = (TextView) convertView.findViewById(R.id.Listaddtocart);
holder.layout = (LinearLayout) convertView.findViewById(R.id.Listcardview);
holder.our_Price = (TextView) convertView.findViewById(R.id.Our_Price);
convertView.setTag(holder);
}else{
holder = (ViewHolder) convertView.getTag();
}
holder.discounted_Value.addTextChangedListener(new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
}
#Override
public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
}
#Override
public void afterTextChanged(Editable editable) {
if(editable.toString().equals("0 % off") | editable.toString().equals("00 % off")){
// 1 - You can set empty text
holder.discounted_Value.setText("");
// 2 - Or you can change the color of the text
holder.discounted_Value.setTextColor(Color.TRANSPARENT);
// 3 - Or you can change the visibility of the view
holder.discounted_Value.setVisibility(View.INVISIBLE);
holder.layout.setVisibility(View.GONE);
}else{
//Here you should undo your code
//1 - if you using method one dose not need to do anything here
// for method 2
holder.discounted_Value.setTextColor(Color.BLACK);
// for method 3
holder.discounted_Value.setVisibility(View.VISIBLE);
holder.layout.setVisibility(View.VISIBLE);
}
}
});
holder.txtText.setText(ActivityMenuList.Menu_name.get(position));
holder.txtSubText.setText("\u20B9" + ActivityMenuList.Menu_price.get(position));
holder.discounted_Price.setText("\u20B9" + ActivityMenuList.Discounted_Price.get(position));
holder.discounted_Value.setText(ActivityMenuList.Discounted_Value.get(position)+ " % off");
holder.our_Price.setText("Our Price" + " " + "\u20B9" + ActivityMenuList.Our_Price.get(position));
Picasso.with(activity).load(Config.ADMIN_PANEL_URL+"/"+ActivityMenuList.Menu_image.get(position)).placeholder(R.drawable.loading).into(holder.imgThumb);
return convertView;
}
static class ViewHolder {
TextView txtText, txtSubText, discounted_Price, quantity, discounted_Value, our_Price;
ImageView imgThumb;
TextView addtocart;
LinearLayout layout;
}
}
Any idea how can i put add to cart button in listview item where i place order from list without opening new activity.
thankx.
Yes it is pretty straight forward to do.
Just add the "add to cart" option in every item itself.
So in the listview, show add to cart at the right most side where the user can click to add to the cart directly.
To get the click, in the base adapter in the getView() method, set the click listener on that holder item(add to cart button) and do the stuff in its onClick.
In my android project i have a listview with items loaded from an online database. When i click on an item i go to another class where i can delete or update it. My problem is that when i press the back button, my listview is empty. I tried onBackPressed with intent to go to previous activity but it is empty again. I want to reload my listview when from a clicked item i press the back button. Below is my code.
The listview:
public class AllStudents extends AppCompatActivity {
ListView StudentListView;
ProgressBar progressBar;
String HttpUrl = "http://sissy-nickels.000webhostapp.com/AllStudentData.php";
List<String> IdList = new ArrayList<>();
String LessonName;
HttpParse httpParse = new HttpParse();
ProgressDialog pDialog;
String FinalJSonObject;
HashMap<String,String> ResultHash = new HashMap<>();
String ParseResult ;
List<Student> studentList;
EditText search;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_allstudents);
StudentListView = (ListView)findViewById(R.id.listview2);
progressBar = (ProgressBar)findViewById(R.id.progressBar);
LessonName = getIntent().getStringExtra("Lesson");
HttpWebCall(LessonName);
//Adding ListView Item click Listener.
StudentListView.setOnItemClickListener(new AdapterView.OnItemClickListener()
{
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
// TODO Auto-generated method stub
Intent intent = new Intent(AllStudents.this,SingleStudent.class);
// Sending ListView clicked value using intent.
intent.putExtra("ListViewValue", IdList.get(position).toString());
startActivity(intent);
//Finishing current activity after open next activity.
//finish();
}
});
search = (EditText)findViewById(R.id.search);
search.addTextChangedListener(new TextWatcher() {
#Override
public void beforeTextChanged (CharSequence s, int start, int count, int after) {
}
// when text is entered in search box, filter list by search text
#Override
public void onTextChanged(CharSequence cs, int start, int before, int count) {
filterStudents(cs);
}
#Override
public void afterTextChanged(Editable s) {
}
});
// check student's name whether contain text entered in search box
}
public void HttpWebCall(final String LessonName){
class HttpWebCallFunction extends AsyncTask<String,Void,String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = ProgressDialog.show(AllStudents.this,"Loading Data",null,true,true);
}
#Override
protected void onPostExecute(String httpResponseMsg) {
super.onPostExecute(httpResponseMsg);
pDialog.dismiss();
//Storing Complete JSon Object into String Variable.
FinalJSonObject = httpResponseMsg ;
//Parsing the Stored JSOn String to GetHttpResponse Method.
new GetHttpResponse(AllStudents.this).execute();
}
#Override
protected String doInBackground(String... params) {
ResultHash.put("LessonName",params[0]);
ParseResult = httpParse.postRequest(ResultHash, HttpUrl);
return ParseResult;
}
}
HttpWebCallFunction httpWebCallFunction = new HttpWebCallFunction();
httpWebCallFunction.execute(LessonName);
}
// JSON parse class started from here.
private class GetHttpResponse extends AsyncTask<Void, Void, Void>
{
public Context context;
public GetHttpResponse(Context context)
{
this.context = context;
}
#Override
protected void onPreExecute()
{
super.onPreExecute();
}
#Override
protected Void doInBackground(Void... arg0)
{
try
{
if(FinalJSonObject != null)
{
JSONArray jsonArray = null;
try {
jsonArray = new JSONArray(FinalJSonObject);
JSONObject jsonObject;
Student student;
studentList = new ArrayList<Student>();
for(int i=0; i<jsonArray.length(); i++)
{
jsonObject = jsonArray.getJSONObject(i);
student = new Student();
// Adding Student Id TO IdList Array.
IdList.add(jsonObject.getString("id").toString());
//Adding Student Name.
student.StudentName = jsonObject.getString("Regnum").toString();
studentList.add(student);
}
}
catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
catch (Exception e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void result)
{
progressBar.setVisibility(View.GONE);
StudentListView.setVisibility(View.VISIBLE);
ListAdapter adapter = new ListAdapter(studentList, context);
StudentListView.setAdapter(adapter);
adapter.notifyDataSetChanged();
}
}
private void filterStudents (CharSequence cs) {
List<Student> filteredList = new ArrayList<>();
if (TextUtils.isEmpty(cs)) {
// no text is entered for search, do nothing
return;
}
// build new student list which filtered by search text.
for (Student student : studentList) {
if (student.StudentName.contains(cs)) {
filteredList.add(student);
}
}
// show filtered list in listview
ListAdapter adapter = new ListAdapter(filteredList, this);
StudentListView.setAdapter(adapter);
adapter.notifyDataSetChanged();
}}
And the code from item click:
public class SingleStudent extends AppCompatActivity {
HttpParse httpParse = new HttpParse();
ProgressDialog pDialog;
// Http Url For Filter Student Data from Id Sent from previous activity.
String HttpURL = "http://sissy-nickels.000webhostapp.com/FilterStudentData.php";
// Http URL for delete Already Open Student Record.
String HttpUrlDeleteRecord = "http://sissy-nickels.000webhostapp.com/DeleteStudent.php";
String finalResult ;
HashMap<String,String> hashMap = new HashMap<>();
String ParseResult ;
HashMap<String,String> ResultHash = new HashMap<>();
String FinalJSonObject ;
TextView NAME,SURNAME,DEPT,REGNUM,GRADE;
String NameHolder, SurnameHolder, DeptHolder, RegnumHolder, GradeHolder;
Button UpdateButton, DeleteButton;
String TempItem;
ProgressDialog progressDialog2;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_singlestudent);
NAME = (TextView)findViewById(R.id.name);
SURNAME = (TextView)findViewById(R.id.surname);
DEPT = (TextView)findViewById(R.id.dept);
REGNUM = (TextView)findViewById(R.id.regnum);
GRADE = (TextView)findViewById(R.id.grade);
UpdateButton = (Button)findViewById(R.id.BDel);
DeleteButton = (Button)findViewById(R.id.BUp);
//Receiving the ListView Clicked item value send by previous activity.
TempItem = getIntent().getStringExtra("ListViewValue");
//Calling method to filter Student Record and open selected record.
HttpWebCall(TempItem);
UpdateButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(SingleStudent.this,StudentUpdate.class);
// Sending Student Id, Name, Number and Class to next UpdateActivity.
intent.putExtra("Id", TempItem);
intent.putExtra("name", NameHolder);
intent.putExtra("surname", SurnameHolder);
intent.putExtra("dept", DeptHolder);
intent.putExtra("regnum", RegnumHolder);
intent.putExtra("grade", GradeHolder);
startActivity(intent);
// Finishing current activity after opening next activity.
finish();
}
});
// Add Click listener on Delete button.
DeleteButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
// Calling Student delete method to delete current record using Student ID.
StudentDelete(TempItem);
}
});
}
// Method to Delete Student Record
public void StudentDelete(final String StudentID) {
class StudentDeleteClass extends AsyncTask<String, Void, String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
progressDialog2 = ProgressDialog.show(SingleStudent.this, "Φόρτωση", null, true, true);
}
#Override
protected void onPostExecute(String httpResponseMsg) {
super.onPostExecute(httpResponseMsg);
progressDialog2.dismiss();
Toast.makeText(SingleStudent.this, httpResponseMsg.toString(), Toast.LENGTH_LONG).show();
finish();
}
#Override
protected String doInBackground(String... params) {
// Sending STUDENT id.
hashMap.put("StudentID", params[0]);
finalResult = httpParse.postRequest(hashMap, HttpUrlDeleteRecord);
return finalResult;
}
}
StudentDeleteClass studentDeleteClass = new StudentDeleteClass();
studentDeleteClass.execute(StudentID);
}
//Method to show current record Current Selected Record
public void HttpWebCall(final String PreviousListViewClickedItem){
class HttpWebCallFunction extends AsyncTask<String,Void,String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = ProgressDialog.show(SingleStudent.this,"Φόρτωση",null,true,true);
}
#Override
protected void onPostExecute(String httpResponseMsg) {
super.onPostExecute(httpResponseMsg);
pDialog.dismiss();
//Storing Complete JSon Object into String Variable.
FinalJSonObject = httpResponseMsg ;
//Parsing the Stored JSOn String to GetHttpResponse Method.
new GetHttpResponse(SingleStudent.this).execute();
}
#Override
protected String doInBackground(String... params) {
ResultHash.put("StudentID",params[0]);
ParseResult = httpParse.postRequest(ResultHash, HttpURL);
return ParseResult;
}
}
HttpWebCallFunction httpWebCallFunction = new HttpWebCallFunction();
httpWebCallFunction.execute(PreviousListViewClickedItem);
}
// Parsing Complete JSON Object.
private class GetHttpResponse extends AsyncTask<Void, Void, Void>
{
public Context context;
public GetHttpResponse(Context context)
{
this.context = context;
}
#Override
protected void onPreExecute()
{
super.onPreExecute();
}
#Override
protected Void doInBackground(Void... arg0)
{
try
{
if(FinalJSonObject != null)
{
JSONArray jsonArray = null;
try {
jsonArray = new JSONArray(FinalJSonObject);
JSONObject jsonObject;
for(int i=0; i<jsonArray.length(); i++)
{
jsonObject = jsonArray.getJSONObject(i);
// Storing Student Name, Phone Number, Class into Variables.
NameHolder = jsonObject.getString("Name").toString() ;
SurnameHolder = jsonObject.getString("Surname").toString() ;
DeptHolder = jsonObject.getString("Dept").toString() ;
RegnumHolder = jsonObject.getString("Regnum").toString() ;
GradeHolder = jsonObject.getString("Grade").toString() ;
}
}
catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
catch (Exception e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void result)
{
// Setting Student Name, Phone Number, Class into TextView after done all process .
NAME.setText(NameHolder);
SURNAME.setText(SurnameHolder);
DEPT.setText(DeptHolder);
REGNUM.setText(RegnumHolder);
GRADE.setText(GradeHolder);
}
}}
Than you in advance!
try this on AllStudents activity
#Override
protected void onResume() {
super.onResume();
if (studentList != null && studentList.size()>0) {
ListAdapter adapter = new ListAdapter(studentList, this);
StudentListView.setAdapter(adapter);
adapter.notifyDataSetChanged();
}
}
*Note
when you make a search you run the filterStudents() method
and replace the current list in the adapter
ListAdapter adapter = new ListAdapter(filteredList, this);
but make sure that if you search for nothing .. return the original list
ListAdapter adapter = new ListAdapter(studentList, this);
or you will get an empty list view
You should not recreate from secondActivity. You just finish it when your work is done in secondActivity. Which means, simply you have to do the below in your secondActivity.
#Override
public void onBackPressed() {
super.onBackPressed();
}
Hello guys i have an issue with my search activit. If i try to search an item for example (iphone 6) and type only "iphone" or "6" or only "i" and other exc... the search works god, but if i put the entire name of the item in this case : iphone 6 , apps crash.
This is the code :
public class SearchActivity extends AppCompatActivity {
Toolbar toolbar;
ListView lsv;
String categoryId,keyword,city;
ProgressDialog progressBar;
List<CatAdd> catAddList;
CateAdDisplayAdapter adapter;
Typeface typeface;
#SuppressLint("NewApi") #Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.activty_search);
toolbar = (Toolbar) findViewById(R.id.toolbar);
if (toolbar != null) {
toolbar.setTitle("Browse Ads");
setSupportActionBar(toolbar);
getSupportActionBar().setHomeButtonEnabled(true);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
}
getActionBarTextView();
typeface = Typeface.createFromAsset(getAssets(), "fonts/GandhiSerif-Bold.otf");
TabLayout tabLayout = (TabLayout) findViewById(R.id.tab_layout);
ViewPager viewPager = (ViewPager) findViewById(R.id.pager);
lsv = (ListView)findViewById(R.id.listView1);
catAddList = new ArrayList<CatAdd>();
categoryId = getIntent().getExtras().getString("categoryId", "0");
keyword = getIntent().getExtras().getString("keyword","keyword");
city = getIntent().getExtras().getString("city","city");
new SearchList().execute();
lsv.setOnItemClickListener(new OnItemClickListener()
{
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
long arg3) {
Intent intent = new Intent(getApplicationContext(), BrowseAdsDetailActivity.class);
intent.putExtra("adId", String.valueOf(catAddList.get(arg2).getAddid()));
startActivity(intent);
}
});
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if(id==android.R.id.home)
{
onBackPressed();
}
return super.onOptionsItemSelected(item);
}
#Override
public void onBackPressed() {
// TODO Auto-generated method stub
super.onBackPressed();
}
private TextView getActionBarTextView() {
TextView titleTextView = null;
try {
Field f = toolbar.getClass().getDeclaredField("mTitleTextView");
f.setAccessible(true);
titleTextView = (TextView)f.get(toolbar);
titleTextView.setTypeface(typeface);
} catch (NoSuchFieldException e) {
} catch (IllegalAccessException e) {
}
return titleTextView;
}
class SearchList extends AsyncTask<Void, Void, Void>
{
String jsonStr = null;
CustomProgressDialog cd = new CustomProgressDialog();
#Override
protected void onPreExecute() {
super.onPreExecute();
cd.showdialog(SearchActivity.this, "Loading...");
}
#Override
protected Void doInBackground(Void... arg0) {
ServiceHandler sh = new ServiceHandler();
jsonStr = sh.makeServiceCall(String.format(Constants.ADSEARCH_URL,categoryId,city,keyword), ServiceHandler.GET);
Log.d("Response: ", "> " + jsonStr);
if (jsonStr != null) {
try {
JSONObject jsonObj = new JSONObject(jsonStr);
JSONArray contacts = jsonObj.getJSONArray(Constants.TAG);
for (int i = contacts.length()-1; i > -1; i--) {
JSONObject c = contacts.getJSONObject(i);
String adId = c.getString(Constants.CAT_ADID);
String adTitle = c.getString(Constants.CAT_ADTITLE);
String adDes = c.getString(Constants.CAT_ADDES);
String adCreatedAt = c.getString("adCreatedAt");
String adcity= c.getString(Constants.CAT_CITY);
String adPrise= c.getString(Constants.CAT_PRICE);
JSONArray arrImages=c.getJSONArray("images");
ArrayList<String> imgArray=new ArrayList<String>();
for(int j=0;j<arrImages.length();j++)
{
JSONObject imgObj=arrImages.getJSONObject(j);
if(imgObj.has("imageName"))
{
imgArray.add(imgObj.getString("imageName"));
}
}
CatAdd v=new CatAdd();
v.setAddid(Integer.parseInt(adId));
v.setAdTitle(adTitle);
v.setAdDesc(adDes);
v.setAdCreatedAt(adCreatedAt);
v.setAdPrice(adPrise);
v.setImglist(imgArray);
v.setAdCity(adcity);
catAddList.add(v);
}
} 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);
cd.dismissdialog();
adapter = new CateAdDisplayAdapter(getApplicationContext(), catAddList);
lsv.setAdapter(adapter);
}
}
Assuming you are making an api call:
You should encode parameters in your url.
String query = URLEncoder.encode("phone 6", "utf-8");
String url = "http://myurl.com/search?q=" + query;
The result would be: http://myurl.com/search?q=phone%206
I'm trying to get the value the user enters in the userNameVar and passwordVar variables, and then compare them to the values stored in my database. However, when I enter the details, which are the same as what I have stored in my database, I get the following message:
Error message
Here is my login class code
public class Login extends AppCompatActivity implements View.OnClickListener {
private EditText usernameField;
private EditText passwordField;
private static Button login_btn;
TextView register_link;
String userNameVar = "";
String passwordVar = "";
private ProgressDialog pDialog;
JSONParser jParser = new JSONParser();
User userObj;
DatabaseUserList databaseUserList = new DatabaseUserList();
private static final String TAG_SUCCESSFUL = "Successful";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.login_page);
login_btn = (Button) findViewById(R.id.login_button);
usernameField = (EditText) findViewById(R.id.etUsername);
passwordField = (EditText) findViewById(R.id.etPassword);
//starts to listen for clicks on this button
login_btn.setOnClickListener(this);
register_link = (TextView) findViewById(R.id.register_link);
register_link.setOnClickListener(this);
}
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.login_button:
//null object reference problem here
Log.d("Username and password",
userNameVar = usernameField.getText().toString();
passwordVar = passwordField.getText().toString();
usernameField.getText().toString());
validateUser(userNameVar, passwordVar);
break;
}
}
private void validateUser (String username, String password)
{
new LogtheuserIn().execute();
}
private void resultsofloginAttmempt(User u)
{
if(u != null)
{
Log.d("User", userObj.toString() + "User must have logged in successfully");
}
}
private void userLoggedIn()
{
Intent intent = new Intent(this, FirstPage.class);
//User has to implement serializable
intent.putExtra("Userisin", userObj);
startActivity(intent);
}
public class LogtheuserIn extends AsyncTask<String,String,String>
{
#Override
protected void onPreExecute()
{
Log.d("onPrexecute", "on the preExecutePart");
pDialog = new ProgressDialog(Login.this);
pDialog.setMessage("Loading users");
pDialog.setIndeterminate(false);
pDialog.setCancelable(false);
pDialog.show();
}
#Override
protected String doInBackground(String... args)
{
List<NameValuePair> arguements = new ArrayList<NameValuePair>();
try{
Log.d("This is the username ", "and password taken from the input fields");
String loginDetails = ServerConnection.SERVER_ADDRESS + "login.php?userName=" + userNameVar + "?password" + passwordVar;
JSONObject jObject = jParser.makeHttpRequest(loginDetails, "GET", arguements);
Log.d("All users", jObject.toString());
int success = jObject.getInt(TAG_SUCCESSFUL);
} catch (Exception e) {
pDialog.dismiss();
runOnUiThread(new Runnable()
{
public void run()
{
Toast.makeText(getApplicationContext(), "Problem with the server",
Toast.LENGTH_SHORT).show();
}
});
}
return null;
}
protected void onPostExecute(String dismissable)
{
//Dismiss the dialogue after we have
//gotten the user(s)
pDialog.dismiss();
Login.this.runOnUiThread(
new Runnable() {
public void run()
{
resultsofloginAttmempt(userObj);
Log.d("Array details", databaseUserList.getListOfUsers().toString());
}
}
);
}
}
#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_login, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
Recheck findViewById(R.id.whatisyourrealid); because it's returning null.
I have a navigation drawer containing 2 items. Now in my first item click, I load data using asynctask and the loaded data is populated in a listview in the corresponding fragment. Now when I switch to 2nd item, again I load data using AsyncTask for the 2nd fragment and show it in in listview.
Now the problem starts. When I go back to the 1st fragment, my
asyncTask is called again and the data is again fetched from the
server, I want to prevent this and load my data directly if it has
been already loaded once.
Please suggest
P.S - Please ask for the code if anyone needs it.
USERPAYFRAGMENT
public class UserPay extends Fragment {
ProgressDialog prg;
Properties prop;
private PrefSingleton mMyPreferences;
private JSONParser jsonParser = new JSONParser();
ArrayList<HashMap<String, String>> RequestList;
HashMap<String, String> map;
UserAdapter req_adp;
ListView req;
private boolean flag;
#Override
public void onAttach(Activity activity) {
// TODO Auto-generated method stub
super.onAttach(activity);
Toast.makeText(getActivity(), "ATTACHED", 1000).show();
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setRetainInstance(true);
Toast.makeText(getActivity(), "CREATE", 1000).show();
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.user_pay, container, false);
initViews(rootView);
Toast.makeText(getActivity(), "ONCREATEVIEW", 1000).show();
return rootView;
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
Toast.makeText(getActivity(), "ONACTIVITYCREATED", 1000).show();
mMyPreferences = PrefSingleton.getInstance();
mMyPreferences.Initialize(getActivity());
RequestList = new ArrayList<HashMap<String, String>>();
Resources resources = this.getResources();
AssetManager assetManager = resources.getAssets();
try {
InputStream inputStream = assetManager.open("jsonURL.properties");
prop = new Properties();
prop.load(inputStream);
} catch (IOException e) {
System.err.println("Failed to open jsonURL property file");
e.printStackTrace();
}
req_adp = new UserAdapter(getActivity(), RequestList);
req.setAdapter(req_adp);
if (!flag) {
new GetRequests().execute();
} else {
}
}
#Override
public void onStart() {
// TODO Auto-generated method stub
super.onStart();
Toast.makeText(getActivity(), "ONSTART", 1000).show();
}
#Override
public void onResume() {
// TODO Auto-generated method stub
super.onResume();
Toast.makeText(getActivity(), "ONRESUME", 1000).show();
}
private void initViews(View v) {
req = (ListView) v.findViewById(R.id.req_list);
}
private class GetRequests extends AsyncTask<Void, Void, Integer> {
#Override
protected void onPreExecute() {
super.onPreExecute();
prg = new ProgressDialog(getActivity());
prg.setIndeterminate(true);
prg.setMessage("Fetching Pending Requests...");
prg.setCanceledOnTouchOutside(false);
prg.show();
}
#Override
protected Integer doInBackground(Void... params) {
List<NameValuePair> params1 = new ArrayList<NameValuePair>();
params1.add(new BasicNameValuePair("userID", mMyPreferences
.getPreference("LoginId")));
String error_code = null;
Log.e("URL ", "is" + prop.getProperty("GET_REQUESTS_URL"));
try {
// getting JSON string from URL
JSONObject json = jsonParser.makeHttpRequest(
Appconstant.GET_REQUESTS_URL, "POST", params1);
// Check your log cat for JSON response
Log.d("Inbox JSON: ", json.toString());
JSONObject jsonObj = json.getJSONObject("data");
error_code = jsonObj.getString("Error_Code");
RequestList.clear();
if ("1".equals(error_code)) {
JSONArray jArray = jsonObj.getJSONArray("result");
for (int i = 0; i < jArray.length(); i++) {
map = new HashMap<String, String>();
JSONObject jsonObj1 = jArray.getJSONObject(i);
String FBankId = jsonObj1
.getString("payment_from_bank_id");
String DestBankId = jsonObj1
.getString("payment_to_bank_id");
String FBank = jsonObj1.getString("fBank");
String TBank = jsonObj1.getString("tBank");
String reason = jsonObj1.getString("payment_reason");
String amt = jsonObj1.getString("amount");
String p_type = jsonObj1.getString("payment_type");
String status = jsonObj1.getString("status");
String r_date = jsonObj1
.getString("request_created_date");
map.put("FBankId", FBankId);
map.put("TBankId", DestBankId);
map.put("SourceBank", FBank);
map.put("DestBank", TBank);
map.put("ReqDate", r_date);
map.put("PayReason", reason);
map.put("Amt", amt);
map.put("PayType", p_type);
map.put("Status", status);
if (status.equals("pending")) {
if (p_type.equals("cheque")
|| p_type.equals("Net Banking")) {
RequestList.add(map);
}
}
}
}
} catch (JSONException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
return Integer.parseInt(error_code);
}
#Override
protected void onPostExecute(Integer result) {
super.onPostExecute(result);
if (prg.isShowing()) {
prg.cancel();
}
if (result == 2) {
Toast.makeText(getActivity(),
"No User Request Details Available.Please Try Again",
Toast.LENGTH_SHORT).show();
}
req_adp.notifyDataSetChanged();
flag = true;
}
}
#Override
public void onPause() {
// TODO Auto-generated method stub
super.onPause();
Toast.makeText(getActivity(), "ONPAUSE",1000).show();
}
#Override
public void onStop() {
// TODO Auto-generated method stub
super.onStop();
Toast.makeText(getActivity(), "ONSTOP", 1000).show();
}
#Override
public void onDestroyView() {
// TODO Auto-generated method stub
super.onDestroyView();
Toast.makeText(getActivity(), "ONDESTROYVIEW", 1000).show();
}
#Override
public void onDestroy() {
// TODO Auto-generated method stub
super.onDestroy();
Toast.makeText(getActivity(), "ONDESTROY", 1000).show();
}
#Override
public void onDetach() {
// TODO Auto-generated method stub
super.onDetach();
Toast.makeText(getActivity(), "ONDETACH", 1000).show();
}
}
There are 2 ways to solve
1 - store the data locally and make use stored data based on appropriate condition checks
2 - If your app is based on this 2 fragments, just create the instance of these fragments and store in in member variable of parent activity. do not give chance to recreate again and again