Progress circle not running till it loads RecyclerView - android

I am trying to move from one activity A to another activity B.In activity B there is a recycler view,In that recycler view I am loading data in background thread(Using AsyncTask) from SQLite database.When I switch to activity B I have given a Progress Bar to show the loading of data.But that progress bar doesn't spin till it fully loads the data.I want it to spin to show loading is happening.
This some what looks like this,
When loading happens then it starts to spin,and looks like this.Running behind the recycler view.
package com.freakydevs.kolkatalocal;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.MenuItem;
import com.google.android.gms.ads.AdRequest;
import com.google.android.gms.ads.AdView;
import java.util.ArrayList;
import java.util.List;
public class TrainTable extends AppCompatActivity {
String from, to;
ProgressDialog progressDialog;
Toolbar toolbar;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.train_table);
toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayShowTitleEnabled(false);
getSupportActionBar().setHomeButtonEnabled(true);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
progressDialog = new ProgressDialog(this, ProgressDialog.THEME_HOLO_DARK);
progressDialog.setMessage("Loading...");
progressDialog.show();
}
#Override
protected void onStart() {
super.onStart();
new MyAsyncTask().execute();
}
public class MyAsyncTask extends AsyncTask<Void, Void, Cursor> {
public int FromStationId, ToStationId;
String sday, sday1, sday2, sday3;
int check = 5;
private List<Train> trainList = new ArrayList<>();
private RecyclerView recyclerView;
private TrainTableAdapter trainTableAdapter;
private RecyclerView.LayoutManager mLayoutManager;
#Override
protected void onPreExecute() {
Intent intent = getIntent();
sday = intent.getStringExtra("day");
from = intent.getStringExtra("From");
to = intent.getStringExtra("To");
FromStationId = intent.getIntExtra("trainId", 0);
ToStationId = intent.getIntExtra("trainId1", 0);
check = intent.getIntExtra("samay", 0);
}
#Override
protected Cursor doInBackground(Void... params) {
//Some codes are here to make a cursor and send it to postExecute
c3 = SQ.rawQuery(s, null);
return c3;
}
#Override
protected void onPostExecute(final Cursor cursor) {
if (cursor.getCount() == 0) {
progressDialog.dismiss();
setProgressBarIndeterminateVisibility(false);
ShowNoTrain();
} else {
recyclerView = (RecyclerView) findViewById(R.id.tiimetable_list);
new Thread(new Runnable() {
#Override
public void run() {
trainTableAdapter = new TrainTableAdapter(TrainTable.this, cursor, from, to);
runOnUiThread(new Runnable() {
#Override
public void run() {
mLayoutManager = new LinearLayoutManager(TrainTable.this);
recyclerView.setLayoutManager(mLayoutManager);
recyclerView.setItemAnimator(new DefaultItemAnimator());
recyclerView.setAdapter(trainTableAdapter);
trainTableAdapter.notifyDataSetChanged();
progressDialog.dismiss();
setProgressBarIndeterminateVisibility(false);
}
});
}
}).start();
}
}
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == android.R.id.home) {
this.finish();
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
protected void onResume() {
super.onResume();
}
public void ShowNoTrain() {
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(TrainTable.this);
// set title
//alertDialogBuilder.setTitle("Invalid Date");
// set dialog message
alertDialogBuilder
.setMessage("No Train Available for this Route!")
.setCancelable(false);
//final AlertDialog my = alertDialogBuilder.create();
alertDialogBuilder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
finish();
}
});
AlertDialog alertDialog = alertDialogBuilder.create();
// create alert dialog
// show it
alertDialog.show();
}
}

Related

setListAdapter() Gone Wrong

When I try to use setListAdapter to show my data this happens:
Cannot resolve method setListAdapter
This is my Activity:
package id.sch.smktelkom.www.crud;
import android.app.ProgressDialog;
import android.content.Intent;
import android.database.Cursor;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.ListView;
import android.widget.Toast;
import java.util.List;
public class CollectionActivity extends AppCompatActivity implements
FetchCollectListener {
String[] daftar;
ListView listView;
protected Cursor cursor;
Button search;
private ProgressDialog dialog;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_collection);
Button btn=(Button)findViewById(R.id.button2);
search = (Button) findViewById(R.id.cari);
initView();
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
Intent inte = new Intent(CollectionActivity.this, MainActivity.class);
startActivity(inte);
}
});
search.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent c = new Intent(CollectionActivity.this, SearchV.class);
startActivity(c);
}
});
}
private void initView() {
// show progress dialog
dialog = ProgressDialog.show(CollectionActivity.this, "", "Loading...");
String url = "http://192.168.4.5/SqliteSync/readC.php";
FetchCollection task = new FetchCollection(this);
task.execute(url);
}
#Override
public void onFetchComplete(List<Collect> data) {
// dismiss the progress dialog
if(dialog != null) dialog.dismiss();
// create new adapter
CollectAdapter adapter = new CollectAdapter(this, data);
// set the adapter to list
setListAdapter(adapter);
}
#Override
public void onFetchFailure(String msg) {
// dismiss the progress dialog
if(dialog != null) dialog.dismiss();
// show failure message
Toast.makeText(this, msg, Toast.LENGTH_LONG).show();
}
}
And this is my Adapter:
package id.sch.smktelkom.www.crud;
import android.content.Context;
import android.content.Intent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageButton;
import android.widget.TextView;
import java.util.List;
public class CollectAdapter extends ArrayAdapter<Collect> {
private List<Collect> items;
private Context mContext;
public CollectAdapter(Context context, List<Collect> items) {
super(context, R.layout.item_collect, items);
this.items = items;
mContext = context;
}
#Override
public int getCount() {
return items.size();
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View v = convertView;
if(v == null) {
LayoutInflater li = LayoutInflater.from(getContext());
v = li.inflate(R.layout.item_collect, null);
}
Collect app = items.get(position);
if(app != null) {
TextView id = (TextView) v.findViewById(R.id.txtpeminjam);
TextView name = (TextView) v.findViewById(R.id.txtpinjaman);
ImageButton btn = (ImageButton) v.findViewById(R.id.list_image);
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent b = new Intent(mContext,LihatDataActivity.class);
mContext.startActivity(b);
}
});
if(id != null) id.setText(app.getNama());
if(name != null) name.setText(app.getPinjaman());
}
return v;
}
}
I don't know what's wrong with this and it's annoying me already.
I want to retrieve data from MySQL to my Android app and when I type setListAdapter suddenly it becomes red and shows some error.
Appreciate any help.
Instead of setListAdapter(adapter); call listView.setAdapter(adapter);
setListAdapter works for activities extending ListActivity
I see also that you should add in onCreate this:
ListView listView=(ListView)findViewById(R.id.listView);
if the name of the ListView is listView in xml
So after some advice from #AmitVikramSingh
I'm referencing my listview
public class CollectionActivity extends AppCompatActivity implements FetchCollectListener {
String[] daftar;
ListView listView;
protected Cursor cursor;
Button search;
private ProgressDialog dialog;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_collection);
Button btn=(Button)findViewById(R.id.button2);
search = (Button) findViewById(R.id.cari);
listView = findViewById(R.id.list);
And I change this from
#Override
public void onFetchComplete(List<Collect> data) {
// dismiss the progress dialog
if(dialog != null) dialog.dismiss();
// create new adapter
CollectAdapter adapter = new CollectAdapter(this, data);
// set the adapter to list
setListAdapter(adapter);
}
To this
#Override
public void onFetchComplete(List<Collect> data) {
// dismiss the progress dialog
if(dialog != null) dialog.dismiss();
// create new adapter
CollectAdapter adapter = new CollectAdapter(this, data);
// set the adapter to list
listView.setAdapter(adapter);
}
Big thanks to all who help me solving this problem

onBackPressed() unfortunately app has stopped in android phone

I am developing an eCommerce application where most of the java class file using Async Task for fetching data from server and I am using fragment in all java class . My problem is that when I click OnBackPressed it shows error in Async Task line because it takes some time interval again to fetch data from server..
MainActivity.java
package com.prashant;
import android.app.SearchManager;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.view.MenuItemCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.SearchView;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.os.Handler;
import android.widget.GridView;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;
import java.util.ArrayList;
import java.util.List;
public class MainActivity extends AppCompatActivity implements android.support.v7.app.ActionBar.OnNavigationListener {
TextView txtView;
private static MainActivity sMainActivity;
ProgressBar prgLoading;
RelativeLayout drawerPane;
DrawerLayout drawerLayout;
GridView lvNav;
TextView Customer_name;
TextView Customer_email;
TextView Customer_mob;
List<NavItem> listNavItems;
List<Fragment> listFragment;
private Boolean exit = false;
ActionBarDrawerToggle actionBarDrawerToggle;
public int hot_number = Constants.ProductCart_Id.size();
private TextView ui_hot = null;
private boolean mNaviFirstHit = true;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
sMainActivity = this;
// Styling Action Bar
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setBackgroundDrawable(new ColorDrawable(Color.rgb(7,112,200)));
drawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
//Getting Session Information Of Customer
String MyPREFERENCES = "CustomerData";
SharedPreferences sharedpreferences =getSharedPreferences(MyPREFERENCES, Context.MODE_PRIVATE);
Constants.Customer_FirstName= sharedpreferences.getString("Customer_FirstName","");
Constants.Customer_LastName=sharedpreferences.getString("Customer_LastName", "");
Constants.Customer_MobileNo=sharedpreferences.getString("Customer_MobileNo", "");
Constants.Customer_Id=sharedpreferences.getInt("Customer_Id", 0);
Constants.Customer_Email=sharedpreferences.getString("Customer_Email", "");
Customer_email.setText(Constants.Customer_Email);
//Asigning FRagment names of sidebar
listNavItems = new ArrayList<NavItem>();
listNavItems.add(new NavItem("Home", null, R.drawable.pras));
for(int i=0;i<Constants.Category_name.size();i++){
listNavItems.add(new NavItem(Constants.Category_name.get(i),null,R.drawable.teju));
}
NavListAdapter navListAdapter = new NavListAdapter(getApplicationContext(), R.layout.item_nav_list, listNavItems);
lvNav.setAdapter(navListAdapter);
listFragment = new ArrayList<Fragment>();
listFragment.add(new MyHome());
for(int i=0;i<Constants.Category_name.size();i++){
listFragment.add(new ProductsListFragment());
}
listFragment.add(new MyHome());
listFragment.add(new ActivityCart());
listFragment.add(new LoginFragment());
listFragment.add(new MyAbout());
//Asigning FRagment names of sidebar
//Saving fragment data as constants for my home categories
Constants.listNavItems=listNavItems;
Constants.listFragment=listFragment;
//Saving fragment data as constants for my home categories
//Load first fragment as default:
FragmentManager fragmentManager = getSupportFragmentManager();
fragmentManager.beginTransaction().replace(R.id.main_content, listFragment.get(0)).commit();
setTitle(listNavItems.get(0).getTitle());
lvNav.setItemChecked(0, true);
drawerLayout.closeDrawer(drawerPane);
// create listener for drawer layout
actionBarDrawerToggle = new ActionBarDrawerToggle(this, drawerLayout, R.string.drawer_open , R.string.drawer_close)
{
#Override
public void onDrawerOpened(View drawerView)
{
invalidateOptionsMenu();
super.onDrawerOpened(drawerView);
}
#Override
public void onDrawerClosed(View drawerView)
{
invalidateOptionsMenu();
super.onDrawerClosed(drawerView);
}
};
drawerLayout.setDrawerListener(actionBarDrawerToggle);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
final Menu mMenu = menu;
MenuInflater mif = getMenuInflater();
mif.inflate(R.menu.actionbar_icon_menu, menu);
// Cart Icon in Action Bar
final View menu_hotlist = menu.findItem(R.id.cart_icon).getActionView();
ui_hot = (TextView) menu_hotlist.findViewById(R.id.hotlist_Cart_hot);
updateHotCount(hot_number);
menu_hotlist.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Constants.lastDetails = false;
FragmentManager fragmentManager = getSupportFragmentManager();
ActivityCart cart = new ActivityCart();
fragmentManager.beginTransaction().replace(R.id.main_content, cart).commit();
setTitle("Cart");
drawerLayout.closeDrawer(drawerPane);
}
});
return super.onCreateOptionsMenu(menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item){
if(actionBarDrawerToggle.onOptionsItemSelected(item))
return true;
// Take appropriate action for each action item click
switch (item.getItemId()) {
case R.id.cart_icon:
// search action
FragmentManager fragmentManager = getSupportFragmentManager();
ActivityCart cart = new ActivityCart();
fragmentManager.beginTransaction().replace(R.id.main_content, cart).commit();
setTitle("Cart");
drawerLayout.closeDrawer(drawerPane);
return true;
case R.id.action_search:
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
protected void onPostCreate(Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
actionBarDrawerToggle.syncState();
}
#Override
public void onBackPressed() {
if (getFragmentManager().getBackStackEntryCount() >0) {
getFragmentManager().popBackStack();
} else {
super.onBackPressed();
}
}
#Override
public boolean onNavigationItemSelected(int itemPosition, long itemId) {
if (mNaviFirstHit) {
mNaviFirstHit = false;
return true;
}
else {
if(itemPosition == 0)
Constants.isCallParent = true;
else
Constants.isCallParent = false;
Constants.SubCatposition = itemPosition;
ProductsListFragment productsListFragment = new ProductsListFragment();
FragmentManager fragmentManager = getSupportFragmentManager();
fragmentManager.beginTransaction().replace(R.id.main_content, productsListFragment).commit();
//lvNav.setItemChecked(position, true);
drawerLayout.closeDrawer(drawerPane);
//Toast.makeText(this, "Clicked at: " + itemPosition, Toast.LENGTH_LONG).show();
//mNaviFirstHit = true;
return true;
}
}
public void setLoginDetails(){
Customer_email.setText(Constants.Customer_Email);
Customer_name.setText("Welcome, " + Constants.Customer_FirstName);
Customer_name.setText(Constants.Customer_LastName);
}
}
ProductListFragment.java
package com.prashant;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.AsyncTask;
import android.support.v4.app.Fragment;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.FragmentManager;
import android.support.v7.app.AppCompatActivity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.GridView;
import org.ksoap2.SoapEnvelope;
import org.ksoap2.serialization.SoapObject;
import org.ksoap2.serialization.SoapSerializationEnvelope;
import org.ksoap2.transport.HttpTransportSE;
import org.xmlpull.v1.XmlPullParserException;
import java.io.IOException;
import java.util.ArrayList;
/**
* Created by prashant.
*/
public class ProductsListFragment extends Fragment {
ProgressDialog pdialog;
View v;
Button sort,filter;
//ListView list;
GridView list;
LazyImageLoadAdapter adapter;
private static ProductsListFragment sProductsListFragment;
// Title navigation Spinner data
private ArrayList<SpinnerNavItem> navSpinner;
// Navigation adapter
private TitleNavigationAdapter titleNavigationAdapter;
#Override
public void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//((AppCompatActivity) getActivity()).getSupportActionBar().setSubtitle(null);
//((MainActivity)getActivity()).actionBarDrawerToggle.setDrawerIndicatorEnabled(true);
// Action Bar
((MainActivity)getActivity()).getSupportActionBar().setDisplayShowTitleEnabled(false);
((MainActivity)getActivity()).getSupportActionBar().setNavigationMode(((MainActivity) getActivity()).getSupportActionBar().NAVIGATION_MODE_LIST);
}
#Override
public View onCreateView(LayoutInflater inflater,#Nullable ViewGroup container,#Nullable Bundle savedInstanceState) {
v = inflater.inflate(R.layout.productlistfragment, container, false);
sProductsListFragment = this;
list=(GridView)v.findViewById(R.id.list);
sort = (Button) v.findViewById(R.id.btn_sort);
sort.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivity(new Intent(getActivity(),Pop.class));
}
});
//clearData();
return v;
}
#Override
public void onResume() {
super.onResume();
((AppCompatActivity) getActivity()).getSupportActionBar().setSubtitle(null);
((MainActivity)getActivity()).actionBarDrawerToggle.setDrawerIndicatorEnabled(true);
}
#Override
public void onPause() {
super.onPause();
((MainActivity)getActivity()).getSupportActionBar().setDisplayShowTitleEnabled(true);
}
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
Constants.cartEntry=0;
//check Product Description fragment is called or not
if (!Constants.lastDetails) {
clearData();
new getDataTask().execute();
}
else{
String[] images=new String[Constants.Product_image.size()];
images=Constants.Product_image.toArray(images);
adapter = new LazyImageLoadAdapter(getActivity(), images);
//Set adapter to listview
list.setAdapter(adapter);
Constants.lastDetails = false;
}
}
// clear arraylist variables before used
void clearData(){
Constants.Product_ID.clear();
Constants.Product_name.clear();
Constants.Product_price.clear();
Constants.Product_image.clear();
Constants.Product_qty.clear();
Constants.Product_specialPrice.clear();
Constants.Product_desc.clear();
}
#Override
public void onDestroy()
{
// Remove adapter refference from list
//list.setAdapter(null);
//Refresh cache directory downloaded images
//adapter.imageLoader.clearCache();
//adapter.notifyDataSetChanged();
super.onDestroy();
}
public View.OnClickListener listener=new View.OnClickListener(){
#Override
public void onClick(View arg0) {
//Refresh cache directory downloaded images
adapter.imageLoader.clearCache();
adapter.notifyDataSetChanged();
}
};
public void onItemClick(int mPosition)
{
/*
Intent intent = new Intent(getActivity(), ProductDescription.class);
intent.putExtra("descposition", mPosition);
startActivity(intent);*/
Constants.product_position = mPosition;
ProductDescription productDescription=new ProductDescription();
getActivity().getSupportFragmentManager().beginTransaction().replace(R.id.main_content, productDescription, null).addToBackStack("productDescription").commit();
//((AppCompatActivity) getActivity()).getSupportActionBar().setSubtitle(Constants.Product_name.get(mPosition));
getActivity().setTitle("Product Details");
}
// Image urls used in LazyImageLoadAdapter.java file
public class getDataTask extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
if (pdialog==null){
pdialog=new ProgressDialog(getActivity());
pdialog.setMessage("Loading...");
pdialog.setCanceledOnTouchOutside(getRetainInstance());
pdialog.setCancelable(false);
pdialog.show();
}
}
#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
// Create custom adapter for listview
String[] images=new String[Constants.Product_image.size()];
images=Constants.Product_image.toArray(images);
adapter = new LazyImageLoadAdapter(getActivity(), images);
//Set adapter to listview
list.setAdapter(adapter);
if (!Constants.isSubCategory) {
Constants.isSubCategory = true;
// Spinner title navigation data
navSpinner = new ArrayList<SpinnerNavItem>();
navSpinner.add(new SpinnerNavItem(Constants.Category_name.get(Constants.position - 1), R.drawable.icon));
for (int i = 0; i < Constants.SubCategory_ID.size(); i++) {
navSpinner.add(new SpinnerNavItem(Constants.SubCategory_name.get(i), R.drawable.icon));
}
// title drop down adapter
titleNavigationAdapter = new TitleNavigationAdapter(getActivity(), navSpinner);
// assigning the spinner navigation
((MainActivity) getActivity()).getSupportActionBar().setListNavigationCallbacks(titleNavigationAdapter, ((MainActivity) getActivity()));
}
if (pdialog.isShowing()){
pdialog.dismiss();
pdialog=null;
}
if (Constants.Product_ID.isEmpty()){
// Toast.makeText(getActivity(), "No products found!!Check your internet connection!!", Toast.LENGTH_LONG).show();
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setTitle("No Product Found!!").setMessage("Slow Internet/Check Your Internet Settings").create().show();
}
/*for (int i = 0; i < Constants.Product_ID.size(); i++) {
Toast.makeText(getActivity(), "__" + Constants.Product_ID.get(i) + "__" + i, Toast.LENGTH_SHORT).show();
}*/
// if internet connection and data available show data on list
// otherwise, show alert text
}
}
// method to parse json data from server
public void parseJSONData(){
SoapObject request = new SoapObject(Constants.NAMESPACE, "catalogCategoryAssignedProducts");
String Catid;
// add paramaters and values
request.addProperty("sessionId", Constants.sessionId);
if ((!Constants.isSubCategory) || Constants.isCallParent) {
Constants.isCallParent = false;
request.addProperty("categoryId", String.valueOf(Constants.Category_ID.get(Constants.position - 1)));
Catid=String.valueOf(Constants.Category_ID.get(Constants.position - 1));
}
else {
request.addProperty("categoryId", String.valueOf(Constants.SubCategory_ID.get(Constants.SubCatposition - 1)));
Catid=String.valueOf(Constants.SubCategory_ID.get(Constants.SubCatposition - 1));
}
api_calls call=new api_calls();
call.getCategoryProducts(Catid);
if (!Constants.isSubCategory) {
Constants.SubCategory_ID.clear();
Constants.SubCategory_name.clear();
parseJSONDataSubCategory();
}
}
// method to parse json data from server
public void parseJSONDataSubCategory(){
try {
SoapObject request = new SoapObject(Constants.NAMESPACE, "catalogCategoryTree");
// add paramaters and values
request.addProperty("sessionId", Constants.sessionId);
request.addProperty("parentId", Constants.Category_ID.get(Constants.position-1));
SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
envelope.dotNet = true;
envelope.setOutputSoapObject(request);
//Web method call
HttpTransportSE androidHttpTransport = new HttpTransportSE(Constants.URL);
androidHttpTransport.debug = true;
androidHttpTransport.call("", envelope);
//get the response
SoapObject result2 = (SoapObject) envelope.getResponse();
SoapObject pii2 = (SoapObject) result2.getProperty(5);
for (int i = 0; i < pii2.getPropertyCount(); i++) {
//JSONObject object = data.getJSONObject(i);
SoapObject pii = (SoapObject)pii2.getProperty(i);
//JSONObject category = object.getJSONObject("Category");
Constants.SubCategory_ID.add(Long.parseLong(pii.getProperty(0).toString()));
Constants.SubCategory_name.add(pii.getProperty(2).toString());
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (XmlPullParserException e) {
e.printStackTrace();
}
}
// Making Sub Drawer for Sub Category
public static ProductsListFragment getInstance() {
return sProductsListFragment;
}
public void onBackPressed()
{
FragmentManager fm = getActivity().getSupportFragmentManager();
fm.popBackStack();
}
}
Logcat
02-11 12:39:57.838 12954-14579/? E/AndroidRuntime: FATAL EXCEPTION: AsyncTask #5
Process: com.softonetech.www.takenick, PID: 12954
java.lang.RuntimeException: An error occurred while executing doInBackground()
at android.os.AsyncTask$3.done(AsyncTask.java:309)
at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:354)
at java.util.concurrent.FutureTask.setException(FutureTask.java:223)
at java.util.concurrent.FutureTask.run(FutureTask.java:242)
at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:234)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1113)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:588)
at java.lang.Thread.run(Thread.java:818)
Caused by: java.lang.ArrayIndexOutOfBoundsException: length=12; index=-1
at java.util.ArrayList.get(ArrayList.java:310)
at com.prashant.ProductsListFragment.parseJSONData(ProductsListFragment.java:250)
at com.prashant.ProductsListFragment$getDataTask.doInBackground(ProductsListFragment.java:185)
at com.prashant.ProductsListFragment$getDataTask.doInBackground(ProductsListFragment.java:167)
at android.os.AsyncTask$2.call(AsyncTask.java:295)
at java.util.concurrent.FutureTask.run(FutureTask.java:237)
at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:234) 
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1113) 
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:588) 
at java.lang.Thread.run(Thread.java:818) 
try cancelling your Async task execution during onBackPressed()
Declare:
Public getDataTask asyncFetchData;
asyncFetchData = new getDataTask();
asyncFetchData.execute();
Now in your Fragment:
#Override
public void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
getView().setFocusableInTouchMode(true);
getView().requestFocus();
getView().setOnKeyListener(new View.OnKeyListener() {
#Override
public boolean onKey(View v, int keyCode, KeyEvent event) {
if (event.getAction() == KeyEvent.ACTION_DOWN) {
if (keyCode == KeyEvent.KEYCODE_BACK) {
if (asyncFetchData!= null)
asyncFetchData.cancel(true);
Toast.makeText(getActivity(), "Back pressed...", Toast.LENGTH_SHORT).show();
return true;
}
}
return false;
}
});
}
Also in doInBackground notify the AsyncTask to cancel execution
#Override
protected Void doInBackground(Void... arg0) {
// TODO Auto-generated method stub
// parse json data from server in background
parseJSONData();
if (isCancelled()) break;
return null;
}

Android - Click on image multiple times to open dialog

I am looking for a code that would let me click on an imageView 3 times to open a dialog box. That would be very helpful, thank you!
Here is my code:
package natanrosenfeld.texteditor;
import android.content.Intent;
import android.support.v7.app.ActionBarActivity;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Toast;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.view.View.OnClickListener;
import com.natanrosenfeld.texteditor.R;
import java.util.concurrent.atomic.AtomicInteger;
import android.os.Handler;
import java.lang.Runnable;
public class CreditsActivity extends ActionBarActivity{
private AtomicInteger mCounter = new AtomicInteger();
private Handler handler = new Handler();
private Runnable mRunnable = new Runnable() {
#Override
public void run() {
mCounter = new AtomicInteger();
}
};
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Utils.onActivityCreateSetTheme(this);
setContentView(R.layout.activity_credits);
ImageView img = (ImageView) findViewById(R.id.imageView);
addClickToImage(img);
}
public void addClickToImage(ImageView imageView) {
imageView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
handler.removeCallbacks(mRunnable);
handler.postDelayed(mRunnable, 1000);
if (mCounter.incrementAndGet() == 2) {
//Display your dialog fragment
new AlertDialog.Builder(getApplicationContext())
.setTitle("Easter Egg")
.setMessage("Easter Egg...")
.setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
// continue with delete
}
})
.setNegativeButton(android.R.string.no, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
// do nothing
}
})
.show();
}
}
});
}
}
ddmlib: Broken pipe
java.io.IOException: Broken pipe
at sun.nio.ch.FileDispatcherImpl.write0(Native Method)
at sun.nio.ch.SocketDispatcher.write(SocketDispatcher.java:47)
at sun.nio.ch.IOUtil.writeFromNativeBuffer(IOUtil.java:93)
at sun.nio.ch.IOUtil.write(IOUtil.java:65)
at sun.nio.ch.SocketChannelImpl.write(SocketChannelImpl.java:487)
at com.android.ddmlib.JdwpPacket.writeAndConsume(JdwpPacket.java:213)
at com.android.ddmlib.Client.sendAndConsume(Client.java:675)
at com.android.ddmlib.HandleHeap.sendREAQ(HandleHeap.java:342)
at com.android.ddmlib.Client.requestAllocationStatus(Client.java:521)
at com.android.ddmlib.DeviceMonitor.createClient(DeviceMonitor.java:847)
at com.android.ddmlib.DeviceMonitor.openClient(DeviceMonitor.java:815)
at
com.android.ddmlib.DeviceMonitor.deviceClientMonitorLoop(DeviceMonitor.java:633)
at com.android.ddmlib.DeviceMonitor.access$100(DeviceMonitor.java:46)
at com.android.ddmlib.DeviceMonitor$3.run(DeviceMonitor.java:592)
Here you have a way to handle the 3 clicks, even if you want to manipulate the counter from other threads. It adds the click listener and waits 1 second to put the counter of clicks to 0.
public class MyActivity extends Activity{
private AtomicInteger mCounter = new AtomicInteger();
private Handle handler = new Handler();
private Runnable mRunnable = new Runnable(){
#Override
public void run(){
mCounter = new AtomicInteger();
}
}
public void onCreate(Bundle savedInstance){
...
ImageView myImage = (ImageView) findViewById(R.id.imageView);
addClickToImage(myImage);
}
public void addClickToImage(ImageView image){
image.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v){
handler.removeCallback(mRunnable);
handler.postDelayed(mRunnable, 1000);
if(mCounter.incrementAndGet() == 3){
//Display your dialog fragment
}
}
});
}
}
Error 2
You are opening your dialog by providing the application context. Here is the line:
new AlertDialog.Builder(getApplicationContext())
The only context that can open dialogs is the current activity context, never the application one. So to fix this error:
new AlertDialog.Builder(CreditsActivity.this)

My ListView acitviity evrytime call previous arraylist when add new data in database

I create an activity thats populate from database and fill to ArrayList.
when add a new data in database and call listview activity thats change ArrayList to last with for example 6 and previous ArrayList with 5 item.
when i finish activity use below code:
Intent intent = new Intent(ListViewClass.this, AddClass.class);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(intent);
ListViewClass.this.onDestroy();
//NamayeshListYadavar.this.finish();
but when call ListViewClass thasts save previous ArrayList and new ArrayList and evrytime switch between two ArrayList.
When i debug my program show me 2 ArrayList with same name but different id and size.how to i can delete previous ArrayList when finish activity and call AddClass in my project?
Also i use
#Override
public void onDestroy() {
super.onDestroy();
Runtime.getRuntime().gc();
}
but in not work.
please help me friends.
and sorry for bad english.
This is all of my oncreate code
all of my code is :
import java.util.ArrayList;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;
import com.blueprogrammers.utils.SomeUtils;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.graphics.Typeface;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.util.TypedValue;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.AdapterView.OnItemClickListener;
public class NamayeshListYadavar extends HeaderFooter {
//AlarmData[] daro_data;
ArrayList<AlarmData> daro_data = new ArrayList<AlarmData>();
Handler mHandler = new Handler();
String myValue;
List<AlarmData> alarmList;
NamayeshListAdaptor adapter;
ListView list;
public String font1="byekan.ttf";
public String font2="BMitraBd.ttf";
private static final int RUN_EDIT = 1100;
/*** 0 for vibre 1 for melody and 2 for melody and vivre***/
int alarmtype = 2, vibre=0;
Boolean animlockBoolean=false;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
ViewGroup vg = (ViewGroup) findViewById(R.id.lldata);
ViewGroup.inflate(this, R.layout.yadavar_list, vg);
list = (ListView) findViewById(R.id.yadavar_listview);
createCollection();
adapter = new NamayeshListAdaptor(this,
R.layout.namayeshyadavar, daro_data);
adapter.notifyDataSetChanged();
list.setAdapter(adapter);
list.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0,
android.view.View arg1, int arg2, long arg3) {
// TODO Auto-generated method stub
TextView tv = (TextView) arg1.findViewById(R.id.txtid);
//String text = tv.getText().toString();
myValue = (String) tv.getText();
Intent intent = new Intent(NamayeshListYadavar.this, EditYadavar.class);
intent.putExtra("YADAVAR-ID", myValue);
startActivity(intent);
NamayeshListYadavar.this.finish();
//startActivityForResult(intent, RUN_EDIT);
}
});
Timer timer = new Timer();
timer.schedule(new TimerTask() {
public void run() {
new textSearh().execute();
}
}, 0, 500);
}
public void clickMe(View v){
switch (v.getId()) {
case R.id.txttarikhetmam:
break;
default:
break;
}
}
class textSearh extends AsyncTask<String, String, String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
}
protected String doInBackground(String... args) {
runOnUiThread(new Runnable() {
public void run() {
final SharedPreferences preferences = getSharedPreferences("DaroPref", 0);
final int del = preferences.getInt("delid", 9999);
Boolean checkBoolean =preferences.getBoolean("delbol", false);
if(checkBoolean){
Editor editor = preferences.edit();
editor.putBoolean("delbol", false);
editor.commit();
deleteView(del);
}
}
});
return null;
}
protected void onPostExecute(String file_url) {
}
}
private void createCollection() {
DatabaseHandler db= new DatabaseHandler(this);
alarmList = new ArrayList<AlarmData>();
alarmList = db.getViewAlarm("SELECT AlarmID, idDrug, alarmTime , nameYadavar, done, alarmDate FROM Alarm where done =0");
ArrayList<AlarmData> alarm_dat = new ArrayList<AlarmData>(alarmList);
this.daro_data=alarm_dat;
db.close();
}
public void deleteView(final int del){
createCollection2();
Animation anim = AnimationUtils.loadAnimation(
NamayeshListYadavar.this, android.R.anim.slide_out_right
);
try{
anim.setDuration(500);
list.getChildAt(del).startAnimation(anim );
new Handler().postDelayed(new Runnable() {
public void run() {
createCollection2();
adapter = new NamayeshListAdaptor(NamayeshListYadavar.this,
R.layout.namayeshyadavar, daro_data);
adapter.notifyDataSetChanged();
list.setAdapter(adapter);
}
}, anim.getDuration());
}catch(Exception e){
e.printStackTrace();
}
}
public void btnbtnClick(View v)
{
switch (v.getId()) {
case R.id.btnadd:
Intent intent = new Intent(NamayeshListYadavar.this, TanzimSaat.class);
intent.putExtra("CLASS-TYPE", "NamayeshListYadavar");
startActivityForResult(intent, RUN_EDIT);
//startActivityForResult(intent, RUN_EDIT);
break;
case R.id.btnbar:
this.finish();
break;
default:
break;
}
}
#Override
public void onBackPressed() {
this.finish();
}
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
switch (requestCode) {
case RUN_EDIT:
createCollection2();
adapter = new NamayeshListAdaptor(this,
R.layout.namayeshyadavar, daro_data);
adapter.notifyDataSetChanged();
list.setAdapter(adapter);
break;
}
}
}
Finally i fixed problem by add below code
public void onBackPressed() {
timer.cancel();
this.finish();
}
Timer is my problem

How to fix setOnItemClickListener inside ListView

I have a ListView which has more rows in it. Inside of rows I have two LinearLayouts (deleteItem and editItem) which has setOnClickListener on them. When I'm trying to click on deleteItem or editItem it works only at the second touch, i don't know why.. I've read some answers on stackoverflow but I couldn't find one answer to fix my problem..
This is the code:
import org.json.JSONArray;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import com.currencymeeting.adapters.GetAllMyCurrencyListViewAdapter;
import com.currencymeeting.beans.User;
import com.currencymeeting.connectors.DeleteCurrencyConnector;
import com.currencymeeting.connectors.MyCurrencyConnector;
import com.currencymeeting.controllers.MessageDialogController;
import com.currencymeeting.controllers.VariableController;
public class MyCurrencyActivity extends FragmentActivity {
private ListView getAllMyCurrencyListView;
private ProgressDialog dialog;
private View view;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_my_currency);
this.dialog = ProgressDialog.show(MyCurrencyActivity.this, MessageDialogController.PROGRESS_DIALOG_TITLE, MessageDialogController.PROGRESS_DIALOG_MESSAGE);
this.getAllMyCurrencyListView = (ListView) findViewById(R.id.getAllMyCurrencyListView);
new GetMyCurrencyResults().execute(new MyCurrencyConnector());
getAllMyCurrencyListView.setOnItemClickListener(
new OnItemClickListener(){
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
MyCurrencyActivity.this.view = view;
final TextView itemID = (TextView) view.findViewById(R.id.itemID);
final LinearLayout deleteItem = (LinearLayout) view.findViewById(R.id.deleteItem);
final LinearLayout editItem = (LinearLayout) view.findViewById(R.id.editItem);
deleteItem.setOnClickListener(
new OnClickListener() {
#Override
public void onClick(View v) {
new AlertDialog.Builder(MyCurrencyActivity.this)
.setMessage("Are you sure do you want to delete it?")
.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
String vid = itemID.getText().toString();
String userId = ""+VariableController.getInstance().getUser().getId();
new DeleteCurrencyTask().execute(userId, vid);
}
})
.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
//do nothing
}
})
.setIcon(android.R.drawable.ic_dialog_alert)
.show();
}
}
);
editItem.setOnClickListener(
new OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(getApplicationContext(),EditCurrencyActivity.class);
startActivity(intent);
}
}
);
}
}
);
final LinearLayout menu = (LinearLayout) findViewById(R.id.menu);
menu.setOnClickListener(
new OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(getApplicationContext(), MenuLoggedActivity.class);
startActivity(intent);
}
}
);
}
public void setListAdapter(JSONArray jsonArray){
this.getAllMyCurrencyListView.setAdapter(new GetAllMyCurrencyListViewAdapter(jsonArray,this));
this.dialog.dismiss();
};
private class GetMyCurrencyResults extends AsyncTask<MyCurrencyConnector,Void,JSONArray>{
#Override
protected JSONArray doInBackground(MyCurrencyConnector... params) {
User user = VariableController.getInstance().getUser();
return params[0].getAllResults(user);
}
#Override
protected void onPostExecute(JSONArray jsonArray) {
setListAdapter(jsonArray);
}
}
private class DeleteCurrencyTask extends AsyncTask<String,Void,String[]>{
#Override
protected String[] doInBackground(String... params) {
return params;
}
#Override
protected void onPostExecute(String[] result) {
boolean status = new DeleteCurrencyConnector().deleteTransaction(result[0],result[1]);
LinearLayout itemViewId = (LinearLayout) MyCurrencyActivity.this.view.findViewById(R.id.itemViewID);
if(status){
new GetMyCurrencyResults().execute(new MyCurrencyConnector());
} else {
Toast.makeText(MyCurrencyActivity.this, "Error", Toast.LENGTH_LONG).show();
}
}
}
}
Your problem might be caused by the way your program executes. You first thread your adapter initialization, and then your main thread starts attaching onclick listeners before your adapter initialization finishes. This means your listview will have a click listener but not the items in the adapter, and when you click the listview once
new GetMyCurrencyResults().execute(new MyCurrencyConnector());
this fires off in your DeleteCurrencyTask and sets the adapter again. To fix this try putting setOnClick initializaion in the post execute of your
private class GetMyCurrencyResults extends AsyncTask<MyCurrencyConnector,Void,JSONArray>{
I believe I realized why the event of deleteItem and editItem is called only on second click, because deleteItem and editItem clickListeners are atached only when getAllMyCurrencyListView.setOnItemClickListener (when I click on row) is called not when the code is loaded. So I guess I have to find another way to make these events

Categories

Resources