How to fix Runtime Exception Unable to start Activity - android

06-28 17:05:23.694 13262-13262/io.hypertrack.sendeta.debug
E/AndroidRuntime: FATAL EXCEPTION: main
Process: io.hypertrack.sendeta.debug, PID: 13262
java.lang.RuntimeException: Unable to start activity ComponentInfo{io.hypertrack.sendeta.debug/io.hypertrack.sendeta.activities.MainActivity}:
android.view.InflateException: Binary XML file line #4: Error
inflating class java.lang.reflect.Constructor
io.hypertrack.sendeta.activities.MainActivity.onCreate(MainActivity.java:109)
public class MainActivity extends AppCompatActivity implements LocationListener {
protected static final int MY_PERMISSIONS_ACCESS_FINE_LOCATION = 1;
// Time in milliseconds; only reload weather if last update is longer ago than this value
private static final int NO_UPDATE_REQUIRED_THRESHOLD = 300000;
private static Map<String, Integer> speedUnits = new HashMap<>(3);
private static Map<String, Integer> pressUnits = new HashMap<>(3);
private static boolean mappingsInitialised = false;
Typeface weatherFont;
Weather todayWeather = new Weather();
TextView todayTemperature;
TextView todayDescription;
TextView todayWind;
TextView todayPressure;
TextView todayHumidity;
TextView todaySunrise;
TextView todaySunset;
TextView lastUpdate;
TextView todayIcon;
ViewPager viewPager;
TabLayout tabLayout;
View appView;
LocationManager locationManager;
ProgressDialog progressDialog;
int theme;
boolean destroyed = false;
private List<Weather> longTermWeather = new ArrayList<>();
private List<Weather> longTermTodayWeather = new ArrayList<>();
private List<Weather> longTermTomorrowWeather = new ArrayList<>();
public String recentCity = "";
#Override
protected void onCreate(Bundle savedInstanceState) {
// Initialize the associated SharedPreferences file with default values
PreferenceManager.setDefaultValues(this, R.xml.prefs, false);
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
setTheme(theme = getTheme(prefs.getString("theme", "fresh")));
boolean darkTheme = theme == R.style.AppTheme_NoActionBar_Dark ||
theme == R.style.AppTheme_NoActionBar_Classic_Dark;
boolean blackTheme = theme == R.style.AppTheme_NoActionBar_Black ||
theme == R.style.AppTheme_NoActionBar_Classic_Black;
// Initiate activity
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_scrolling);
appView = findViewById(R.id.viewApp);
progressDialog = new ProgressDialog(MainActivity.this);
// Load toolbar
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
if (darkTheme) {
toolbar.setPopupTheme(R.style.AppTheme_PopupOverlay_Dark);
} else if (blackTheme) {
toolbar.setPopupTheme(R.style.AppTheme_PopupOverlay_Black);
}
// Initialize textboxes
todayTemperature = (TextView) findViewById(R.id.todayTemperature);
todayDescription = (TextView) findViewById(R.id.todayDescription);
todayWind = (TextView) findViewById(R.id.todayWind);
todayPressure = (TextView) findViewById(R.id.todayPressure);
todayHumidity = (TextView) findViewById(R.id.todayHumidity);
todaySunrise = (TextView) findViewById(R.id.todaySunrise);
todaySunset = (TextView) findViewById(R.id.todaySunset);
lastUpdate = (TextView) findViewById(R.id.lastUpdate);
todayIcon = (TextView) findViewById(R.id.todayIcon);
weatherFont = Typeface.createFromAsset(this.getAssets(), "fonts/weather.ttf");
todayIcon.setTypeface(weatherFont);
// Initialize viewPager
viewPager = (ViewPager) findViewById(R.id.viewPager);
tabLayout = (TabLayout) findViewById(R.id.tabs);
destroyed = false;
initMappings();
// Preload data from cache
preloadWeather();
updateLastUpdateTime();
// Set autoupdater
AlarmReceiver.setRecurringAlarm(this);
}
public WeatherRecyclerAdapter getAdapter(int id) {
WeatherRecyclerAdapter weatherRecyclerAdapter;
if (id == 0) {
weatherRecyclerAdapter = new WeatherRecyclerAdapter(this, longTermTodayWeather);
} else if (id == 1) {
weatherRecyclerAdapter = new WeatherRecyclerAdapter(this, longTermTomorrowWeather);
} else {
weatherRecyclerAdapter = new WeatherRecyclerAdapter(this, longTermWeather);
}
return weatherRecyclerAdapter;
}
#Override
public void onStart() {
super.onStart();
updateTodayWeatherUI();
updateLongTermWeatherUI();
}
#Override
public void onResume() {
super.onResume();
if (getTheme(PreferenceManager.getDefaultSharedPreferences(this).getString("theme", "fresh")) != theme) {
// Restart activity to apply theme
overridePendingTransition(0, 0);
finish();
overridePendingTransition(0, 0);
startActivity(getIntent());
} else if (shouldUpdate() && isNetworkAvailable()) {
getTodayWeather();
getLongTermWeather();
}
}
#Override
protected void onDestroy() {
super.onDestroy();
destroyed = true;
if (locationManager != null) {
try {
locationManager.removeUpdates(MainActivity.this);
} catch (SecurityException e) {
e.printStackTrace();
}
}
}
private void preloadWeather() {
SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(MainActivity.this);
String lastToday = sp.getString("lastToday", "");
if (!lastToday.isEmpty()) {
new TodayWeatherTask(this, this, progressDialog).executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, "cachedResponse", lastToday);
}
String lastLongterm = sp.getString("lastLongterm", "");
if (!lastLongterm.isEmpty()) {
new LongTermWeatherTask(this, this, progressDialog).executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, "cachedResponse", lastLongterm);
}
}
private void getTodayWeather() {
new TodayWeatherTask(this, this, progressDialog).execute();
}
private void getLongTermWeather() {
new LongTermWeatherTask(this, this, progressDialog).execute();
}
private void searchCities() {
AlertDialog.Builder alert = new AlertDialog.Builder(this);
alert.setTitle(this.getString(R.string.search_title));
final EditText input = new EditText(this);
input.setInputType(InputType.TYPE_CLASS_TEXT);
input.setMaxLines(1);
input.setSingleLine(true);
alert.setView(input, 32, 0, 32, 0);
alert.setPositiveButton(R.string.dialog_ok, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
String result = input.getText().toString();
if (!result.isEmpty()) {
saveLocation(result);
}
}
});
alert.setNegativeButton(R.string.dialog_cancel, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
// Cancelled
}
});
alert.show();
}
private void saveLocation(String result) {
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(MainActivity.this);
recentCity = preferences.getString("city", Constants.DEFAULT_CITY);
SharedPreferences.Editor editor = preferences.edit();
editor.putString("city", result);
editor.commit();
if (!recentCity.equals(result)) {
// New location, update weather
getTodayWeather();
getLongTermWeather();
}
}
private void aboutDialog() {
AlertDialog.Builder alert = new AlertDialog.Builder(this);
alert.setTitle("Forecastie");
final WebView webView = new WebView(this);
String about = "<p>1.6.1</p>" +
"<p>A lightweight, opensource weather app.</p>" +
"<p>Developed by <a href='mailto:t.martykan#gmail.com'>Tomas Martykan</a></p>" +
"<p>Data provided by <a href='https://openweathermap.org/'>OpenWeatherMap</a>, under the <a href='http://creativecommons.org/licenses/by-sa/2.0/'>Creative Commons license</a>" +
"<p>Icons are <a href='https://erikflowers.github.io/weather-icons/'>Weather Icons</a>, by <a href='http://www.twitter.com/artill'>Lukas Bischoff</a> and <a href='http://www.twitter.com/Erik_UX'>Erik Flowers</a>, under the <a href='http://scripts.sil.org/OFL'>SIL OFL 1.1</a> licence.";
TypedArray ta = obtainStyledAttributes(new int[]{android.R.attr.textColorPrimary, R.attr.colorAccent});
String textColor = String.format("#%06X", (0xFFFFFF & ta.getColor(0, Color.BLACK)));
String accentColor = String.format("#%06X", (0xFFFFFF & ta.getColor(1, Color.BLUE)));
ta.recycle();
about = "<style media=\"screen\" type=\"text/css\">" +
"body {\n" +
" color:" + textColor + ";\n" +
"}\n" +
"a:link {color:" + accentColor + "}\n" +
"</style>" +
about;
webView.setBackgroundColor(Color.TRANSPARENT);
webView.loadData(about, "text/html", "UTF-8");
alert.setView(webView, 32, 0, 32, 0);
alert.setPositiveButton(R.string.dialog_ok, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
}
});
alert.show();
}
private String setWeatherIcon(int actualId, int hourOfDay) {
int id = actualId / 100;
String icon = "";
if (actualId == 800) {
if (hourOfDay >= 7 && hourOfDay < 20) {
icon = this.getString(R.string.weather_sunny);
} else {
icon = this.getString(R.string.weather_clear_night);
}
} else {
switch (id) {
case 2:
icon = this.getString(R.string.weather_thunder);
break;
case 3:
icon = this.getString(R.string.weather_drizzle);
break;
case 7:
icon = this.getString(R.string.weather_foggy);
break;
case 8:
icon = this.getString(R.string.weather_cloudy);
break;
case 6:
icon = this.getString(R.string.weather_snowy);
break;
case 5:
icon = this.getString(R.string.weather_rainy);
break;
}
}
return icon;
}
public static String getRainString(JSONObject rainObj) {
String rain = "0";
if (rainObj != null) {
rain = rainObj.optString("3h", "fail");
if ("fail".equals(rain)) {
rain = rainObj.optString("1h", "0");
}
}
return rain;
}
private ParseResult parseTodayJson(String result) {
try {
JSONObject reader = new JSONObject(result);
final String code = reader.optString("cod");
if ("404".equals(code)) {
return ParseResult.CITY_NOT_FOUND;
}
String city = reader.getString("name");
String country = "";
JSONObject countryObj = reader.optJSONObject("sys");
if (countryObj != null) {
country = countryObj.getString("country");
todayWeather.setSunrise(countryObj.getString("sunrise"));
todayWeather.setSunset(countryObj.getString("sunset"));
}
todayWeather.setCity(city);
todayWeather.setCountry(country);
JSONObject coordinates = reader.getJSONObject("coord");
if (coordinates != null) {
SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(this);
sp.edit().putFloat("latitude", (float) coordinates.getDouble("lon")).putFloat("longitude", (float) coordinates.getDouble("lat")).commit();
}
JSONObject main = reader.getJSONObject("main");
todayWeather.setTemperature(main.getString("temp"));
todayWeather.setDescription(reader.getJSONArray("weather").getJSONObject(0).getString("description"));
JSONObject windObj = reader.getJSONObject("wind");
todayWeather.setWind(windObj.getString("speed"));
if (windObj.has("deg")) {
todayWeather.setWindDirectionDegree(windObj.getDouble("deg"));
} else {
Log.e("parseTodayJson", "No wind direction available");
todayWeather.setWindDirectionDegree(null);
}
todayWeather.setPressure(main.getString("pressure"));
todayWeather.setHumidity(main.getString("humidity"));
JSONObject rainObj = reader.optJSONObject("rain");
String rain;
if (rainObj != null) {
rain = getRainString(rainObj);
} else {
JSONObject snowObj = reader.optJSONObject("snow");
if (snowObj != null) {
rain = getRainString(snowObj);
} else {
rain = "0";
}
}
todayWeather.setRain(rain);
final String idString = reader.getJSONArray("weather").getJSONObject(0).getString("id");
todayWeather.setId(idString);
todayWeather.setIcon(setWeatherIcon(Integer.parseInt(idString), Calendar.getInstance().get(Calendar.HOUR_OF_DAY)));
SharedPreferences.Editor editor = PreferenceManager.getDefaultSharedPreferences(MainActivity.this).edit();
editor.putString("lastToday", result);
editor.commit();
} catch (JSONException e) {
Log.e("JSONException Data", result);
e.printStackTrace();
return ParseResult.JSON_EXCEPTION;
}
return ParseResult.OK;
}
private void updateTodayWeatherUI() {
try {
if (todayWeather.getCountry().isEmpty()) {
preloadWeather();
return;
}
} catch (Exception e) {
preloadWeather();
return;
}
String city = todayWeather.getCity();
String country = todayWeather.getCountry();
DateFormat timeFormat = android.text.format.DateFormat.getTimeFormat(getApplicationContext());
getSupportActionBar().setTitle(city + (country.isEmpty() ? "" : ", " + country));
SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(MainActivity.this);
// Temperature
float temperature = UnitConvertor.convertTemperature(Float.parseFloat(todayWeather.getTemperature()), sp);
if (sp.getBoolean("temperatureInteger", false)) {
temperature = Math.round(temperature);
}
// Rain
double rain = Double.parseDouble(todayWeather.getRain());
String rainString = UnitConvertor.getRainString(rain, sp);
// Wind
double wind;
try {
wind = Double.parseDouble(todayWeather.getWind());
} catch (Exception e) {
e.printStackTrace();
wind = 0;
}
wind = UnitConvertor.convertWind(wind, sp);
// Pressure
double pressure = UnitConvertor.convertPressure((float) Double.parseDouble(todayWeather.getPressure()), sp);
todayTemperature.setText(new DecimalFormat("0.#").format(temperature) + " " + sp.getString("unit", "°C"));
todayDescription.setText(todayWeather.getDescription().substring(0, 1).toUpperCase() +
todayWeather.getDescription().substring(1) + rainString);
if (sp.getString("speedUnit", "m/s").equals("bft")) {
todayWind.setText(getString(R.string.wind) + ": " +
UnitConvertor.getBeaufortName((int) wind) +
(todayWeather.isWindDirectionAvailable() ? " " + getWindDirectionString(sp, this, todayWeather) : ""));
} else {
todayWind.setText(getString(R.string.wind) + ": " + new DecimalFormat("0.0").format(wind) + " " +
localize(sp, "speedUnit", "m/s") +
(todayWeather.isWindDirectionAvailable() ? " " + getWindDirectionString(sp, this, todayWeather) : ""));
}
todayPressure.setText(getString(R.string.pressure) + ": " + new DecimalFormat("0.0").format(pressure) + " " +
localize(sp, "pressureUnit", "hPa"));
todayHumidity.setText(getString(R.string.humidity) + ": " + todayWeather.getHumidity() + " %");
todaySunrise.setText(getString(R.string.sunrise) + ": " + timeFormat.format(todayWeather.getSunrise()));
todaySunset.setText(getString(R.string.sunset) + ": " + timeFormat.format(todayWeather.getSunset()));
todayIcon.setText(todayWeather.getIcon());
}
public ParseResult parseLongTermJson(String result) {
int i;
try {
JSONObject reader = new JSONObject(result);
final String code = reader.optString("cod");
if ("404".equals(code)) {
if (longTermWeather == null) {
longTermWeather = new ArrayList<>();
longTermTodayWeather = new ArrayList<>();
longTermTomorrowWeather = new ArrayList<>();
}
return ParseResult.CITY_NOT_FOUND;
}
longTermWeather = new ArrayList<>();
longTermTodayWeather = new ArrayList<>();
longTermTomorrowWeather = new ArrayList<>();
JSONArray list = reader.getJSONArray("list");
for (i = 0; i < list.length(); i++) {
Weather weather = new Weather();
JSONObject listItem = list.getJSONObject(i);
JSONObject main = listItem.getJSONObject("main");
weather.setDate(listItem.getString("dt"));
weather.setTemperature(main.getString("temp"));
weather.setDescription(listItem.optJSONArray("weather").getJSONObject(0).getString("description"));
JSONObject windObj = listItem.optJSONObject("wind");
if (windObj != null) {
weather.setWind(windObj.getString("speed"));
weather.setWindDirectionDegree(windObj.getDouble("deg"));
}
weather.setPressure(main.getString("pressure"));
weather.setHumidity(main.getString("humidity"));
JSONObject rainObj = listItem.optJSONObject("rain");
String rain = "";
if (rainObj != null) {
rain = getRainString(rainObj);
} else {
JSONObject snowObj = listItem.optJSONObject("snow");
if (snowObj != null) {
rain = getRainString(snowObj);
} else {
rain = "0";
}
}
weather.setRain(rain);
final String idString = listItem.optJSONArray("weather").getJSONObject(0).getString("id");
weather.setId(idString);
final String dateMsString = listItem.getString("dt") + "000";
Calendar cal = Calendar.getInstance();
cal.setTimeInMillis(Long.parseLong(dateMsString));
weather.setIcon(setWeatherIcon(Integer.parseInt(idString), cal.get(Calendar.HOUR_OF_DAY)));
Calendar today = Calendar.getInstance();
if (cal.get(Calendar.DAY_OF_YEAR) == today.get(Calendar.DAY_OF_YEAR)) {
longTermTodayWeather.add(weather);
} else if (cal.get(Calendar.DAY_OF_YEAR) == today.get(Calendar.DAY_OF_YEAR) + 1) {
longTermTomorrowWeather.add(weather);
} else {
longTermWeather.add(weather);
}
}
SharedPreferences.Editor editor = PreferenceManager.getDefaultSharedPreferences(MainActivity.this).edit();
editor.putString("lastLongterm", result);
editor.commit();
} catch (JSONException e) {
Log.e("JSONException Data", result);
e.printStackTrace();
return ParseResult.JSON_EXCEPTION;
}
return ParseResult.OK;
}
private void updateLongTermWeatherUI() {
if (destroyed) {
return;
}
ViewPagerAdapter viewPagerAdapter = new ViewPagerAdapter(getSupportFragmentManager());
Bundle bundleToday = new Bundle();
bundleToday.putInt("day", 0);
RecyclerViewFragment recyclerViewFragmentToday = new RecyclerViewFragment();
recyclerViewFragmentToday.setArguments(bundleToday);
viewPagerAdapter.addFragment(recyclerViewFragmentToday, getString(R.string.today));
Bundle bundleTomorrow = new Bundle();
bundleTomorrow.putInt("day", 1);
RecyclerViewFragment recyclerViewFragmentTomorrow = new RecyclerViewFragment();
recyclerViewFragmentTomorrow.setArguments(bundleTomorrow);
viewPagerAdapter.addFragment(recyclerViewFragmentTomorrow, getString(R.string.tomorrow));
Bundle bundle = new Bundle();
bundle.putInt("day", 2);
RecyclerViewFragment recyclerViewFragment = new RecyclerViewFragment();
recyclerViewFragment.setArguments(bundle);
viewPagerAdapter.addFragment(recyclerViewFragment, getString(R.string.later));
int currentPage = viewPager.getCurrentItem();
viewPagerAdapter.notifyDataSetChanged();
viewPager.setAdapter(viewPagerAdapter);
tabLayout.setupWithViewPager(viewPager);
if (currentPage == 0 && longTermTodayWeather.isEmpty()) {
currentPage = 1;
}
viewPager.setCurrentItem(currentPage, false);
}
private boolean isNetworkAvailable() {
ConnectivityManager connectivityManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
return activeNetworkInfo != null && activeNetworkInfo.isConnected();
}
private boolean shouldUpdate() {
long lastUpdate = PreferenceManager.getDefaultSharedPreferences(this).getLong("lastUpdate", -1);
boolean cityChanged = PreferenceManager.getDefaultSharedPreferences(this).getBoolean("cityChanged", false);
// Update if never checked or last update is longer ago than specified threshold
return cityChanged || lastUpdate < 0 || (Calendar.getInstance().getTimeInMillis() - lastUpdate) > NO_UPDATE_REQUIRED_THRESHOLD;
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
}

Related

Items not displaying orderwise in Recycler View

In my Recycler View not displaying the item orderwise routinely changing the items for each and every time while running the program.
How to display Order wise the items in Recycler View.
Code:
final CustomLinearLayoutManagercartpage layoutManager = new CustomLinearLayoutManagercartpage(CartItems.this, LinearLayoutManager.VERTICAL, false);
recyleitems.setHasFixedSize(false);
recyleitems.setLayoutManager(layoutManager);
cartadapter = new CartlistAdapter(cart, CartItems.this);
Log.i(String.valueOf(cartadapter), "cartadapter");
recyleitems.setAdapter(cartadapter);
recyleitems.setNestedScrollingEnabled(false);
myView.setVisibility(View.GONE);
cartadapter.notifyDataSetChanged();
Adapter:
public class CartlistAdapter extends RecyclerView.Adapter < CartlistAdapter.ViewHolder > {
private ArrayList < CartItemoriginal > cartlistadp;
private ArrayList < Cartitemoringinaltwo > cartlistadp2;
DisplayImageOptions options;
private Context context;
public static final String MyPREFERENCES = "MyPrefs";
public static final String MYCARTPREFERENCE = "CartPrefs";
public static final String MyCartQtyPreference = "Cartatyid";
SharedPreferences.Editor editor;
SharedPreferences shared,
wishshared;
SharedPreferences.Editor editors;
String pos,
qtyDelete;
String date;
String currentDateandTime;
private static final int VIEW_TYPE_ONE = 1;
private static final int VIEW_TYPE_TWO = 2;
private static final int TYPE_HEADER = 0;
private Double orderTotal = 0.00;
DecimalFormat df = new DecimalFormat("0");
Double extPrice;
View layout,
layouts;
SharedPreferences sharedPreferences;
SharedPreferences.Editor QutId;
boolean flag = false;
public CartlistAdapter() {
}
public CartlistAdapter(ArrayList < CartItemoriginal > cartlistadp, Context context) {
this.cartlistadp = cartlistadp;
this.cartlistadp2 = cartlistadp2;
this.context = context;
options = new DisplayImageOptions.Builder().cacheOnDisk(true).cacheInMemory(true).showImageOnLoading(R.drawable.b2)
.showImageForEmptyUri(R.drawable.b2).build();
if (YelloPage.imageLoader.isInited()) {
YelloPage.imageLoader.destroy();
}
YelloPage.imageLoader.init(ImageLoaderConfiguration.createDefault(context));
}
public int getItemViewType(int position) {
if (cartlistadp.size() == 0) {
Toast.makeText(context, String.valueOf(cartlistadp), Toast.LENGTH_LONG).show();
return VIEW_TYPE_TWO;
}
return VIEW_TYPE_ONE;
}
#Override
public CartlistAdapter.ViewHolder onCreateViewHolder(ViewGroup viewGroup, int position) {
ViewHolder viewHolder = null;
switch (position) {
case VIEW_TYPE_TWO:
View view2 = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.activity_cart, viewGroup, false);
viewHolder = new ViewHolder(view2, new MyTextWatcher(viewGroup, position));
// return view holder for your placeholder
break;
case VIEW_TYPE_ONE:
View view = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.cartitemrow, viewGroup, false);
viewHolder = new ViewHolder(view, new MyTextWatcher(view, position));
// return view holder for your normal list item
break;
}
return viewHolder;
}
#Override
public void onBindViewHolder(CartlistAdapter.ViewHolder viewHolder, int position) {
viewHolder.productnames.setText(cartlistadp.get(position).getProductname());
viewHolder.cartalisname.setText(cartlistadp.get(position).getAliasname());
viewHolder.cartprice.setText("Rs" + " " + cartlistadp.get(position).getPrice());
viewHolder.cartdelivery.setText(cartlistadp.get(position).getDelivery());
viewHolder.cartshippin.setText(cartlistadp.get(position).getShippincharge());
viewHolder.cartsellername.setText(cartlistadp.get(position).getSellername());
viewHolder.Error.setText(cartlistadp.get(position).getError());
viewHolder.qty.setTag(cartlistadp.get(position));
viewHolder.myTextWatcher.updatePosition(position);
if (cartlistadp.get(position).getQty() != 0) {
viewHolder.qty.setText(String.valueOf(cartlistadp.get(position).getQty()));
viewHolder.itemView.setTag(viewHolder);
} else {
viewHolder.qty.setText("0");
}
YelloPage.imageLoader.displayImage(cartlistadp.get(position).getProductimg(), viewHolder.cartitemimg, options);
}
#Override
public int getItemCount() {
return cartlistadp.size();
}
public long getItemId(int position) {
return position;
}
public Object getItem(int position) {
return cartlistadp.get(position);
}
public class ViewHolder extends RecyclerView.ViewHolder {
private TextView productnames, cartalisname, cartprice, cartdelivery, cartshippin, cartsellername, Error, total;
private ImageView cartitemimg;
private ImageButton wishbtn, removebtn;
private LinearLayout removecart, movewishlist;
private CardView cd;
private EditText qty;
private ImageView WishImg;
public MyTextWatcher myTextWatcher;
public ViewHolder(final View view, MyTextWatcher myTextWatcher) {
super(view);
productnames = (TextView) view.findViewById(R.id.cartitemname);
cartalisname = (TextView) view.findViewById(R.id.cartalias);
cartprice = (TextView) view.findViewById(R.id.CartAmt);
cartdelivery = (TextView) view.findViewById(R.id.cartdel);
cartshippin = (TextView) view.findViewById(R.id.shippingcrg);
cartsellername = (TextView) view.findViewById(R.id.cartSellerName);
cartitemimg = (ImageView) view.findViewById(R.id.cartimg);
Error = (TextView) view.findViewById(R.id.error);
this.myTextWatcher = myTextWatcher;
removecart = (LinearLayout) view.findViewById(R.id.removecart);
movewishlist = (LinearLayout) view.findViewById(R.id.movewishlist);
WishImg = (ImageView) view.findViewById(R.id.wishimg);
qty = (EditText) view.findViewById(R.id.quantity);
qty.addTextChangedListener(myTextWatcher);
String pid, qid;
sharedPreferences = view.getContext().getSharedPreferences(MYCARTPREFERENCE, Context.MODE_PRIVATE);
QutId = sharedPreferences.edit();
Log.d("Position checking1 ---", String.valueOf(getAdapterPosition()));
//MyTextWatcher textWatcher = new MyTextWatcher(view,qty);
// qty.addTextChangedListener(new MyTextWatcher(view,getAdapterPosition()));
//qty.addTextChangedListener(textWatcher);
qty.setOnKeyListener(new View.OnKeyListener() {
#Override
public boolean onKey(View v, int keyCode, KeyEvent event) {
qty.setSelection(qty.getText().length());
return false;
}
});
wishshared = view.getContext().getSharedPreferences(MyPREFERENCES, context.MODE_PRIVATE);
editors = view.getContext().getSharedPreferences(MyPREFERENCES, context.MODE_PRIVATE).edit();
shared = view.getContext().getSharedPreferences(MYCARTPREFERENCE, context.MODE_PRIVATE);
editor = view.getContext().getSharedPreferences(MYCARTPREFERENCE, context.MODE_PRIVATE).edit();
cd = (CardView) view.findViewById(R.id.cv);
productnames.setSingleLine(false);
productnames.setEllipsize(TextUtils.TruncateAt.END);
productnames.setMaxLines(2);
//totalPrice();
view.setClickable(true);
// view.setFocusableInTouchMode(true);
removecart.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (cartlistadp.size() == 1) {
Intent list = new Intent(v.getContext(), Cart.class);
context.startActivity(list);
((Activity) context).finish();
removeAt(getAdapterPosition());
Log.i(String.valueOf(getPosition()), "item");
Toast.makeText(context, "All items deleted from your WishList", Toast.LENGTH_LONG).show();
} else {
removeAt(getAdapterPosition());
}
}
});
MovewishList();
totalPrice();
}
private void totalPrice() {
int price = 0;
for (int j = 0; j < cartlistadp.size(); j++) {
price += Integer.parseInt(cartlistadp.get(j).getPrice()) * (cartlistadp.get(j).getQty());
String totalprice = String.valueOf(price);
String count = String.valueOf(cartlistadp.size());
CartItems.Totalamt.setText(totalprice);
CartItems.cartcount.setText("(" + count + ")");
CartItems.carttotalcount.setText("(" + count + ")");
}
}
public void removeAt(int positions) {
JSONArray test = new JSONArray();
JSONArray test1 = new JSONArray();
JSONArray test2 = new JSONArray();
JSONArray item = null;
JSONArray itemsQty = null;
test1.put("0");
test2.put("0");
test.put(test1);
test.put(test2);
String channel = shared.getString(Constants.cartid, String.valueOf(test));
pos = cartlistadp.get(getAdapterPosition()).getProductid();
qtyDelete = String.valueOf(cartlistadp.get(getAdapterPosition()).getQty());
try {
JSONArray delteitems = new JSONArray(channel);
itemsQty = delteitems.getJSONArray(0);
item = delteitems.getJSONArray(1);
for (int x = 0; x < itemsQty.length(); x++) {
if (pos.equalsIgnoreCase(itemsQty.getString(x))) {
itemsQty.remove(x);
cartlistadp.remove(positions);
notifyItemRemoved(positions);
notifyItemRangeChanged(positions, cartlistadp.size());
notifyDataSetChanged();
}
}
for (int y = 0; y < item.length(); y++) {
if (qtyDelete.equalsIgnoreCase(item.getString(y)))
item.remove(y);
}
String s = String.valueOf(delteitems);
editor.putString(Constants.cartid, String.valueOf(delteitems));
editor.apply();
} catch (JSONException e) {
e.printStackTrace();
}
}
public void MovewishList() {
movewishlist.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (cartlistadp.size() == 1) {
pos = cartlistadp.get(getAdapterPosition()).getProductid();
JSONArray items3;
if (!flag) {
// wishlist.setBackgroundResource(R.drawable.wishnew);
flag = true;
String channel = wishshared.getString(Constants.productid, "['']");
JSONArray items;
String wishitem;
if (TextUtils.isEmpty(channel)) {
items = new JSONArray();
items.put(String.valueOf(pos));
wishitem = String.valueOf(items);
editors.putString(Constants.productid, wishitem);
editors.apply();
removeAt(getAdapterPosition());
Toast.makeText(context, "cartItems", Toast.LENGTH_LONG).show();
flag = false;
} else {
try {
Boolean found = false;
items = new JSONArray(channel);
for (int x = 0; x < items.length(); x++) {
if (pos.equalsIgnoreCase(items.getString(x))) {
found = true;
removeAt(getAdapterPosition());
Toast.makeText(context, "cartItems1", Toast.LENGTH_LONG).show();
}
}
if (!found) {
items.put(String.valueOf(pos));
wishitem = String.valueOf(items);
editors.putString(Constants.productid, wishitem);
removeAt(getAdapterPosition());
Toast.makeText(context, Constants.productid, Toast.LENGTH_LONG).show();
Log.i(Constants.productid, "wishitems");
}
editors.apply();
flag = false;
} catch (JSONException e) {
e.printStackTrace();
}
}
Intent list = new Intent(view.getContext(), Cart.class);
context.startActivity(list);
((Activity) context).finish();
} else {
removeAt(getAdapterPosition());
Intent list = new Intent(view.getContext(), Cart.class);
context.startActivity(list);
((Activity) context).finish();
}
} else {
pos = cartlistadp.get(getAdapterPosition()).getProductid();
if (!flag) {
// wishlist.setBackgroundResource(R.drawable.wishnew);
flag = true;
String channel = wishshared.getString(Constants.productid, "['']");
JSONArray items;
String wishitem;
if (TextUtils.isEmpty(channel)) {
items = new JSONArray();
items.put(String.valueOf(pos));
wishitem = String.valueOf(items);
editors.putString(Constants.productid, wishitem);
editors.apply();
removeAt(getAdapterPosition());
Toast.makeText(context, "cartItems", Toast.LENGTH_LONG).show();
flag = false;
} else {
try {
Boolean found = false;
items = new JSONArray(channel);
for (int x = 0; x < items.length(); x++) {
if (pos.equalsIgnoreCase(items.getString(x))) {
found = true;
removeAt(getAdapterPosition());
}
}
if (!found) {
items.put(String.valueOf(pos));
wishitem = String.valueOf(items);
editors.putString(Constants.productid, wishitem);
removeAt(getAdapterPosition());
Log.i(Constants.productid, "wishitems");
}
editors.apply();
flag = false;
} catch (JSONException e) {
e.printStackTrace();
}
}
} else {
removeAt(getAdapterPosition());
}
}
}
});
}
}
public class InputFilterMinMax implements InputFilter {
private int min, max;
public InputFilterMinMax(int min, int max) {
this.min = min;
this.max = max;
}
public InputFilterMinMax(String min, String max) {
this.min = Integer.parseInt(min);
this.max = Integer.parseInt(max);
}
#Override
public CharSequence filter(CharSequence source, int start, int end, Spanned dest, int dstart, int dend) {
try {
int input = Integer.parseInt(dest.toString() + source.toString());
if (isInRange(min, max, input))
return null;
} catch (NumberFormatException nfe) {}
return "";
}
private boolean isInRange(int a, int b, int c) {
return b > a ? c >= a && c <= b : c >= b && c <= a;
}
}
private class MyTextWatcher implements TextWatcher {
private View view;
private EditText editText;
private int position;
//private int position;
private MyTextWatcher(View view, int position) {
this.view = view;
this.position = position;
// this.position = adapterPosition;
// cartlistadp.get(position).getQty() = Integer.parseInt((Caption.getText().toString()));
}
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
//do nothing
}
public void onTextChanged(CharSequence s, int start, int before, int count) {
// EditText qtyView = (EditText) view.findViewById(R.id.quantity);
Log.i("editextpostion", String.valueOf(position));
}
public void afterTextChanged(Editable s) {
DecimalFormat df = new DecimalFormat("0");
String qtyString = s.toString();
int quantity = qtyString.equals("") ? 0 : Integer.valueOf(qtyString);
String quty = String.valueOf(quantity);
EditText qtyView = (EditText) view.findViewById(R.id.quantity);
CartItemoriginal product = (CartItemoriginal) qtyView.getTag();
// int position = (int) view.qtyView.getTag();
Log.d("postion is qtytag", "Position is: " + product);
qtyView.setFilters(new InputFilter[] {
new InputFilterMinMax(product.getMinquantity(), product.getMaxquantity())
});
if (product.getQty() != quantity) {
Double currPrice = product.getExt();
Double price = Double.parseDouble(product.getPrice());
int maxaty = Integer.parseInt(product.getMaxquantity());
int minqty = Integer.parseInt(product.getMinquantity());
if (quantity < maxaty) {
extPrice = quantity * price;
} else {
Toast.makeText(context, "Sorry" + " " + " " + "we are shipping only" + " " + " " + maxaty + " " + " " + "unit of quantity", Toast.LENGTH_LONG).show();
}
Double priceDiff = Double.valueOf(df.format(extPrice - currPrice));
product.setQty(quantity);
product.setExt(extPrice);
TextView ext = (TextView) view.findViewById(R.id.CartAmt);
if (product.getQty() != 0) {
ext.setText("Rs." + " " + df.format(product.getExt()));
} else {
ext.setText("0");
}
if (product.getQty() != 0) {
qtyView.setText(String.valueOf(product.getQty()));
} else {
qtyView.setText("");
}
JSONArray test = new JSONArray();
JSONArray test1 = new JSONArray();
JSONArray test2 = new JSONArray();
JSONArray items = null;
JSONArray itemsQty = null;
test1.put("0");
test2.put("0");
test.put(test1);
test.put(test2);
JSONArray listitems = null;
//String Sharedqty= String.valueOf(cartlistadp.get(getAdapterPosition()).getQty());
String channel = (shared.getString(Constants.cartid, String.valueOf(test)));
try {
listitems = new JSONArray(channel);
itemsQty = listitems.getJSONArray(1);
} catch (JSONException e) {
e.printStackTrace();
}
try {
if (itemsQty != null) {
itemsQty.put(position + 1, qtyString);
}
} catch (JSONException e) {
e.printStackTrace();
}
try {
if (listitems != null) {
listitems.put(1, itemsQty);
}
} catch (JSONException e) {
e.printStackTrace();
}
QutId.putString(Constants.cartid, String.valueOf(listitems));
QutId.apply();
Toast.makeText(context, String.valueOf(listitems), Toast.LENGTH_SHORT).show();
totalPrice();
}
return;
}
private void totalPrice() {
int price = 0;
for (int j = 0; j < cartlistadp.size(); j++) {
price += Integer.parseInt(cartlistadp.get(j).getPrice()) * (cartlistadp.get(j).getQty());
String totalprice = String.valueOf(price);
String count = String.valueOf(cartlistadp.size());
CartItems.Totalamt.setText(totalprice);
CartItems.cartcount.setText("(" + count + ")");
CartItems.carttotalcount.setText("(" + count + ")");
}
}
public void updatePosition(int position) {
this.position = position;
}
}
}
Thanks in Advance.
For sorting you need to Collection.sort method of Java and also you need to implement comparable interface for define your comparison.
CartItemoriginal implements Comparable {
public int compareTo(Object obj) { } }
Updated
public class CartItemoriginal implements Comparable<CartItemoriginal > {
private Float val;
private String id;
public CartItemoriginal (Float val, String id){
this.val = val;
this.id = id;
}
#Override
public int compareTo(ToSort f) {
if (val.floatValue() > f.val.floatValue()) {
return 1;
}
else if (val.floatValue() < f.val.floatValue()) {
return -1;
}
else {
return 0;
}
}
#Override
public String toString(){
return this.id;
}
}
and use
Collections.sort(sortList);

Using AlertDialog.Builder to build custom AlertDialog class

I have a Class FoodDialog that extends AlertDialog that I have customized to how I would like it to look.
I am now wanting to edit the positive/negative buttons using an AlertDialog.Builder, however, when I attempt to build an instance of FoodDialog using a builder, I am facing an 'Incompatible types' error where the builder is asking for AlertDialog instead I am providing it with an extension of AlertDialog - is there a way around this?
If not, is there a way I can edit the positive/negative buttons of my custom AlertDialog class FoodDialog?
Below is my FoodDialog class. The yes/no buttons I have there are ones I have created myself, but I would like the ones that are part of the AlertDialog.Builder to appear instead as these buttons get pushed out of sight when the soft keyboard appears:
public class FoodDialog extends AlertDialog implements OnClickListener {
private TextView foodNameTextView, foodDescTextView, foodPortionTextView, catTextView, qtyText, cal, fat, sFat, carb, sug, prot, salt, imageTxt,
measureText;
private EditText foodQty;
private ImageView foodImage;
private ImageButton yesBtn, noBtn;
private int foodID, totalCal;
private Bitmap image;
private String user, portionType, foodName, foodDesc, cat, totalCalString, totalFatString,
totalSFatString, totalCarbString, totalSugString, totalProtString, totalSaltString, portionBaseString;
private double totalFat, totalSFat, totalCarb, totalSug, totalProt, totalSalt, portionBase;
private Food food;
private Portion portion;
private Nutrients nutrients;
private PortionType pType;
private DBHandler db;
public FoodDialog(Context context){
super(context);
}
public FoodDialog(Context context, int foodID, String imgLocation, final String user) {
super(context, android.R.style.Theme_Holo_Light_Dialog);
this.setTitle("Confirm?");
setContentView(R.layout.dialog_layout);
this.foodID = foodID;
this.user = user;
db = new DBHandler(context);
food = db.getFoodByID(foodID, user);
portion = db.getPortionByFoodID(foodID);
nutrients = db.getNutrientsByFoodIDAndPortionType(foodID, portion.getPortionType());
pType = db.getPortionTypeByName(portion.getPortionType());
//getting object attributes
portionType = portion.getPortionType();
portionBase = portion.getPortionBase();
//food
foodName = food.getName();
foodDesc = food.getDesc();
cat = food.getCat();
//nutrients
totalCal = nutrients.getCal();
totalFat = nutrients.getFat();
totalSFat = nutrients.getSFat();
totalCarb = nutrients.getCarb();
totalSug = nutrients.getSug();
totalProt = nutrients.getProt();
totalSalt = nutrients.getSalt();
//converting to string
totalCalString = String.valueOf(totalCal);
if (totalFat % 1 == 0) {
totalFatString = String.format("%.0f", totalFat);
} else {
totalFatString = String.valueOf(totalFat);
}
if (totalSFat % 1 == 0) {
totalSFatString = String.format("%.0f", totalSFat);
} else {
totalSFatString = String.valueOf(totalSFat);
}
if (totalCarb % 1 == 0) {
totalCarbString = String.format("%.0f", totalCarb);
} else {
totalCarbString = String.valueOf(totalCarb);
}
if (totalSug % 1 == 0) {
totalSugString = String.format("%.0f", totalSug);
} else {
totalSugString = String.valueOf(totalSug);
}
if (totalProt % 1 == 0) {
totalProtString = String.format("%.0f", totalProt);
} else {
totalProtString = String.valueOf(totalProt);
}
if (totalSalt % 1 == 0) {
totalSaltString = String.format("%.0f", totalSalt);
} else {
totalSaltString = String.valueOf(totalSalt);
}
if (portionBase % 1 == 0) {
portionBaseString = String.format("%.0f", portionBase);
} else {
portionBaseString = String.valueOf(portionBase);
}
//textviews
foodNameTextView = (TextView) findViewById(R.id.dialogName);
foodNameTextView.setText(foodName);
foodDescTextView = (TextView) findViewById(R.id.dialogDesc);
foodDescTextView.setText(foodDesc);
foodPortionTextView = (TextView) findViewById(R.id.dialogPortion);
foodPortionTextView.setText("Values based per " + portionBase + " " + portionType);
catTextView = (TextView) findViewById(R.id.dialogCat);
catTextView.setText(cat);
measureText = (TextView) findViewById(R.id.dialogMeasure);
measureText.setText(portionType);
qtyText = (TextView) findViewById(R.id.dialogQtyText);
imageTxt = (TextView) findViewById(R.id.dialogImageText);
cal = (TextView) findViewById(R.id.dialogCal);
cal.setText(totalCalString);
fat = (TextView) findViewById(R.id.dialogFat);
fat.setText(totalFatString + "g");
sFat = (TextView) findViewById(R.id.dialogSFat);
sFat.setText(totalSFatString + "g");
carb = (TextView) findViewById(R.id.dialogCarb);
carb.setText(totalCarbString + "g");
sug = (TextView) findViewById(R.id.dialogSug);
sug.setText(totalSugString + "g");
prot = (TextView) findViewById(R.id.dialogProt);
prot.setText(totalProtString + "g");
salt = (TextView) findViewById(R.id.dialogSalt);
salt.setText(totalSaltString + "g");
//img
foodImage = (ImageView) findViewById(R.id.dialogImage);
imgLocation = food.getImgURL();
image = BitmapFactory.decodeFile(imgLocation);
foodImage.setImageBitmap(image);
if (imgLocation.equals("nourl")) {
imageTxt.setText("No Image");
}
//edit tex
foodQty = (EditText) findViewById(R.id.dialogQty);
//adjusting edittext
foodQty.setInputType(InputType.TYPE_CLASS_NUMBER | InputType.TYPE_NUMBER_FLAG_DECIMAL);
foodQty.setFilters(new InputFilter[]{
new DigitsKeyListener(Boolean.FALSE, Boolean.TRUE) {
int beforeDecimal = 4, afterDecimal = 3;
#Override
public CharSequence filter(CharSequence source, int start, int end,
Spanned dest, int dstart, int dend) {
String temp = foodQty.getText() + source.toString();
if (temp.equals(".")) {
return "0.";
} else if (temp.toString().indexOf(".") == -1) {
// no decimal point placed yet
if (temp.length() > beforeDecimal) {
return "";
}
} else {
temp = temp.substring(temp.indexOf(".") + 1);
if (temp.length() > afterDecimal) {
return "";
}
}
return super.filter(source, start, end, dest, dstart, dend);
}
}
});
foodQty.setText(portionBaseString);
//btns
yesBtn = (ImageButton) findViewById(R.id.yesBtn);
noBtn = (ImageButton) findViewById(R.id.noBtn);
Bitmap tick = BitmapFactory.decodeResource(context.getResources(),
R.drawable.png_tick);
Bitmap cross = BitmapFactory.decodeResource(context.getResources(),
R.drawable.png_cross);
yesBtn.setImageBitmap(tick);
noBtn.setImageBitmap(cross);
yesBtn.setOnClickListener(this);
noBtn.setOnClickListener(this);
getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE);
}
#Override
public void onClick(View v) {
if (v == yesBtn) {
SimpleDateFormat currentDate = new SimpleDateFormat("yyyy-MM-dd");
SimpleDateFormat currentTime = new SimpleDateFormat("HH:mm:ss");
String date = currentDate.format(new Date());
String time = currentTime.format(new Date());
double qty = 0;
//get quantity amount
// if (portionMeasure.equals("singles")) {
//qty = foodQty.getValue();
// } else {
if (foodQty.getText().length() != 0) {
qty = Double.valueOf(foodQty.getText().toString());
} else {
qty = 0;
}
// }
if (qty == 0 || String.valueOf(qty) == "") {
Toast.makeText(getContext(), "Please enter an amount", Toast.LENGTH_SHORT).show();
} else {
//create new intake
Intake intake = new Intake(0, foodID, portionType, qty, date, time);
//record it and increment food used value
db.recordIntake(intake, user);
db.incrementUsedCount(intake.getFoodID(), 1);
db.close();
cancel();
Toast.makeText(getContext(), foodName + " recorded", Toast.LENGTH_SHORT).show();
AlertDialog.Builder builder = new AlertDialog.Builder(getContext());
builder.setTitle("What next?");
builder.setItems(new CharSequence[]
{"Record another food intake..", "Main Menu..", "View Stats.."},
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
// The 'which' argument contains the index position
// of the selected item
switch (which) {
case 0:
cancel();
break;
case 1:
Intent main = new Intent(getContext(), ProfileActivity.class);
getContext().startActivity(main);
break;
case 2:
Intent stats = new Intent(getContext(), StatsActivity.class);
getContext().startActivity(stats);
break;
}
}
});
AlertDialog choose = builder.create();
choose.show();
}
} else if (v == noBtn) {
cancel();
}
}
}
You can catch your buttons click listener as follows:
yesBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//yes button click code here
}
});
noBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//no button click code here
}
});
You can use the logcat to see if your listener are being fired.

How do I use onResume and onPause method when I am pressed back button

I have a custom adapter for recyclerview using json webservices. I had to parse the url one by one and show cardview using onscrolllistener(). My question is when I pressed the back button and after I open in recent app (that time onResume called) it will show only which url called at the time of onPause called. So how can I refresh the listview when I call onResume.
Thanks in Advance,
Here my code synepet..
public class MainActivity extends AppCompatActivity {
private RecyclerView mRecyclerView;
private RecyclerView.Adapter mAdapter;
private GridLayoutManager mGridManager;
private ProgressBar mProgressBar;
private static String url = "https://www.googleapis.com/youtube/v3/playlists?part=snippet&channelId=UCGyZswzm4G-wEfRQHgMSAuw&maxResults=50&key=AIzaSyCi0ApXYk08YpzyEO8jYJanaud-Epti6ks&pageToken=CDIQAQ";
JSONArray contacts = null;
private String mNextToken;
JSONObject jsonObj;
private boolean loading = true;
int visibleItemCount, totalItemCount, pastVisiblesItems;
private List<PlayListItem> mContactList = new ArrayList<PlayListItem>();
private PlayListItem mContact;
private Bundle mbundle;
String name2 = "Arasu";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
mProgressBar = (ProgressBar) findViewById(R.id.progressBar);
mRecyclerView = (RecyclerView) findViewById(R.id.recycler_view);
mRecyclerView.setHasFixedSize(true);
// Calling async task to get json
new GetContacts().execute();
mAdapter = new CardAdapter(MainActivity.this, mContactList);
mRecyclerView.setAdapter(mAdapter);
getScreenOrientation();
}
#Override
public void onResume() {
super.onResume();
}
#Override
protected void onPause() {
super.onPause();
System.out.println("Size2---->" + mContactList.size());
}
private class GetContacts extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
// Showing progress dialog
mProgressBar.setVisibility(View.VISIBLE);
mProgressBar.setMax(100);
}
#Override
protected Void doInBackground(Void... arg0) {
// Creating service handler class instance
ServiceHandler sh = new ServiceHandler();
// Making a request to url and getting response
String jsonArray = sh.makeServiceCall(url, ServiceHandler.GET);
//Log.d("Response: ", "> " + jsonArray);
if (jsonArray != null) {
try {
jsonObj = new JSONObject(jsonArray);
if (jsonObj.has("nextPageToken")) {
loading = true;
mNextToken = jsonObj.getString("nextPageToken");
} else {
loading = false;
}
// Getting JSON Array node
contacts = jsonObj.getJSONArray("items");
// looping through All Contacts
for (int i = 0; i < contacts.length(); i++) {
JSONObject c = contacts.getJSONObject(i);
String title = c.getJSONObject("snippet").getString("title");
String time = c.getJSONObject("snippet").getString("publishedAt");
String playlist_id = c.get("id").toString();
// Find Screen size and set the Image for this size
DisplayMetrics dm = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(dm);
double x = Math.pow(dm.widthPixels / dm.xdpi, 2);
double y = Math.pow(dm.heightPixels / dm.ydpi, 2);
double screenInches = Math.sqrt(x + y);
int inch = (int) Math.round(screenInches);
String image = null;
try {
if (inch <= 4) {
image = c.getJSONObject("snippet").getJSONObject("thumbnails").getJSONObject("medium").getString("url");
} else if (inch > 4 && inch <= 6) {
image = c.getJSONObject("snippet").getJSONObject("thumbnails").getJSONObject("medium").getString("url");
} else if (inch > 6 && inch <= 10) {
image = c.getJSONObject("snippet").getJSONObject("thumbnails").getJSONObject("medium").getString("url");
} else {
image = c.getJSONObject("snippet").getJSONObject("thumbnails").getJSONObject("default").getString("url");
}
} catch (IndexOutOfBoundsException e) {
e.printStackTrace();
}
mContact = new PlayListItem();
mContact.setmTitle(title);
mContact.setmID(playlist_id);
mContact.setmTime(time);
mContact.setmThumbnailURL(image);
mContact.setmNextToken(mNextToken);
mContactList.add(mContact);
}
} catch (JSONException e) {
e.printStackTrace();
}
} else {
Log.e("ServiceHandler", "Couldn't get any data from the url");
}
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
// Dismiss the progress dialog
if (mProgressBar.isShown())
mProgressBar.setVisibility(ProgressBar.GONE);
mAdapter.notifyDataSetChanged();
mRecyclerView.setOnScrollListener(new RecyclerView.OnScrollListener() {
#Override
public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
super.onScrolled(recyclerView, dx, dy);
visibleItemCount = mGridManager.getChildCount();
totalItemCount = mGridManager.getItemCount();
pastVisiblesItems = mGridManager.findFirstVisibleItemPosition();
if (loading) {
if ((visibleItemCount + pastVisiblesItems) >= totalItemCount) {
Log.v("...", "Last Item Wow !");
if (jsonObj.has("nextPageToken")) {
url = "https://www.googleapis.com/youtube/v3/playlists?part=snippet&channelId=UCGyZswzm4G-wEfRQHgMSAuw&maxResults=50&key=AIzaSyCi0ApXYk08YpzyEO8jYJanaud-Epti6ks&pageToken=" + mNextToken;
System.out.println("url--->" + url);
new GetContacts().execute();
} else {
url = "https://www.googleapis.com/youtube/v3/playlists?part=snippet&channelId=UCGyZswzm4G-wEfRQHgMSAuw&maxResults=50&key=AIzaSyCi0ApXYk08YpzyEO8jYJanaud-Epti6ks&pageToken=" + mNextToken;
System.out.println("url----else--->" + url);
new GetContacts().execute();
}
loading = false;
}
}
}
});
}
}
}
public class CardAdapter extends RecyclerView.Adapter<CardAdapter.ViewHolder> {
private List<PlayListItem> mItems;
private Activity activity;
public ImageLoader imageLoader;
public CardAdapter(Activity activity, List<PlayListItem> items) {
this.activity = activity;
this.mItems = items;
imageLoader = new ImageLoader(activity.getApplicationContext());
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup viewGroup, int i) {
View v = LayoutInflater.from(viewGroup.getContext())
.inflate(R.layout.recycler_outer_playlist_cardview, viewGroup, false);
ViewHolder viewHolder = new ViewHolder(v);
return viewHolder;
}
#Override
public void onBindViewHolder(ViewHolder viewHolder, final int i) {
System.out.println("Title Value is----------->"+mItems.get(0));
PlayListItem nature = mItems.get(i);
Log.d("Title Value is","----------->"+nature.getmTitle());
viewHolder.tvTitle.setText(nature.getmTitle());
final String playListID = nature.getmID();
final String thumnailsURL = nature.getmThumbnailURL();
final Calendar c = Calendar.getInstance();
int cur_year = c.get(Calendar.YEAR);
int cur_month = c.get(Calendar.MONTH) + 1;
int cur_day = c.get(Calendar.DAY_OF_MONTH);
int cur_hour = c.get(Calendar.HOUR_OF_DAY);
int cur_minute = c.get(Calendar.MINUTE);
// Getting updated date from url
String string = nature.getmTime();
String[] parts = string.split("-");
String part1 = parts[0]; // 004
String part2 = parts[1]; // 034556
String part3 = parts[2];
String[] part4 = part3.split("T");
String part5 = part4[0];
String part6 = part4[1];
// Toast.makeText(activity, "Given Date is : " + part1 + "/" + part2 + "/" + part3, Toast.LENGTH_LONG).show();
// Log.d("Updated Current Day", part5);
int giv_yr = Integer.parseInt(part1);
int giv_mnt = Integer.parseInt(part2);
int giv_day = Integer.parseInt(part5);
// Difference Two dates
int day_yr = 0, day_mnt = 0, day_day = 0;
if (cur_year >= giv_yr) {
if (cur_year >= giv_yr) {
day_yr = cur_year - giv_yr;
} else {
day_yr = giv_yr - cur_year;
}
if (cur_month >= giv_mnt) {
day_mnt = cur_month - giv_mnt;
} else {
day_mnt = giv_mnt - cur_month;
}
if (cur_day >= giv_day) {
day_day = cur_day - giv_day;
} else {
day_day = giv_day - cur_day;
}
}
String yr = Integer.toString(day_yr);
String mnt = Integer.toString(day_mnt);
String days = Integer.toString(day_day);
if (day_day == 0)
viewHolder.tvTime.setText("Updated Today");
else if (day_day < 7)
viewHolder.tvTime.setText("Updated " + days + " Days ago");
else if (day_day < 30) {
int week = day_day / 7;
String Week = Integer.toString(week);
viewHolder.tvTime.setText("Updated " + Week + " Weeks ago");
} else {
viewHolder.tvTime.setText("Updated " + mnt + " Months ago");
}
//imageLoader.DisplayImage(nature.getmThumbnailURL(), viewHolder.imgThumbnail);
Picasso.with(activity)
.load(nature.getmThumbnailURL())
/*.placeholder(R.drawable.my_thumnail)*/
.into(viewHolder.imgThumbnail);
viewHolder.item_view.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(activity, VideoPlayActivity.class);
intent.putExtra("PLAYLIST_ID", playListID);
intent.putExtra("THUMNAIL_URL", thumnailsURL);
v.getContext().startActivity(intent);
}
});
/*System.out.println("URL -------------->"+nature.getmThumbnailURL());
// String img_url = nature.getmThumbnailURL();
try {
URL url = new URL(nature.getmThumbnailURL());
Bitmap bmp = BitmapFactory.decodeStream(url.openConnection().getInputStream());
System.out.println("Image bmp -------------->"+bmp);
//imageView.setImageBitmap(bmp);
viewHolder.imgThumbnail.setImageBitmap(bmp);
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}*/
}
#Override
public int getItemCount() {
return mItems.size();
}
class ViewHolder extends RecyclerView.ViewHolder {
public ImageView imgThumbnail;
public TextView tvTitle;
public TextView tvID;
public TextView tvTime;
public View item_view;
public ViewHolder(View itemView) {
super(itemView);
imgThumbnail = (ImageView) itemView.findViewById(R.id.img_thumbnail);
tvTitle = (TextView) itemView.findViewById(R.id.tv_title);
//tvID = (TextView) itemView.findViewById(R.id.tv_id);
tvTime = (TextView) itemView.findViewById(R.id.tv_time);
item_view = itemView;
}
}
}
I made a small mistake declaring String URL as static but it should be final also assign to another String variable. Finally set the adapter and notifyDataSetChanged where placed in onStart().
private final static String URL = "https://www.googleapis.com/youtube/v3/playlists?part=snippet&channelId=UCGyZswzm4G-wEfRQHgMSAuw&maxResults=50&key=AIzaSyCi0ApXYk08YpzyEO8jYJanaud-Epti6ks&pageToken=CDIQAQ";
private String url = URL;
JSONArray contacts = null;
private String mNextToken;
JSONObject jsonObj;
private boolean loading = true;
int visibleItemCount, totalItemCount, pastVisiblesItems;
private List<PlayListItem> mContactList;
private PlayListItem mContact;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
mProgressBar = (ProgressBar) findViewById(R.id.progressBar);
mRecyclerView = (RecyclerView) findViewById(R.id.recycler_view);
mRecyclerView.setHasFixedSize(true);
// Calling async task to get json
if (mContactList == null)
mContactList = new ArrayList<PlayListItem>();
System.out.println("onCreate :: Size2---->" + mContactList.size());
}
#Override
protected void onStart() {
super.onStart();
if (mContactList != null)
mContactList.clear();
url = URL;
new GetContacts().execute();
if (mAdapter == null)
mAdapter = new CardAdapter(MainActivity.this, mContactList);
mRecyclerView.setAdapter(mAdapter);
mAdapter.notifyDataSetChanged();
getScreenOrientation();
System.out.println("onStart :: Size2---->" + mContactList.size());
}
#Override
protected void onResume() {
ActivitySwitcher.animationIn(findViewById(R.id.container_first),
getWindowManager());
super.onResume();
System.out.println("onResume :: Size2---->" + mContactList.size());
mAdapter.notifyDataSetChanged();
}

email extractor android program crashes aide

public class MainActivity extends Activity {
public static LinearLayout layout = null;
public static EditText urlstring = null;
public static Button submit = null;
public static ListView emailsfound = null;
public static ArrayList<String> emaillist = new ArrayList<String>();
public static ArrayList<String> urllist = new ArrayList<String>();
public static ArrayAdapter<String> adapter = null;
/**
* Called when the activity is first created.
*/
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
layout = new LinearLayout(this);
urlstring = new EditText(this);
submit = new Button(this);
submit.setText("Submit");
emailsfound = new ListView(this);
layout.setOrientation(LinearLayout.VERTICAL);
layout.addView(urlstring);
layout.addView(submit);
layout.addView(emailsfound);
setContentView(layout);
adapter = new ArrayAdapter(this, android.R.layout.simple_list_item_1, emaillist);
emailsfound.setAdapter(adapter);
submit.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
urllist.add(urlstring.getText().toString());
int i = 0;
while (true) {
String page = getPage(urlstring.getText().toString());
ArrayList<String> urls = new ArrayList<String>();
urls = getURLs(page);
ArrayList<String> addresses = new ArrayList<String>();
addresses = getAddresses(page);
for (int a = 0; i < urls.size(); i++) {
urllist.add(urls.get(a));
}
for (int a = 0; a < addresses.size(); i++) {
emaillist.add(addresses.get(a));
}
removeDuplicates(urllist);
removeDuplicates(emaillist);
adapter.notifyDataSetChanged();
i++;
urlstring.setText(urllist.get(i).toString());
}
}
;
});
}
public String getPage(String url) {
if (url.toLowerCase().startsWith("http") == false) {
url = "http://" + url;
}
URL fromstring = null;
URLConnection openConnection = null;
try {
fromstring = new URL(url);
openConnection = fromstring.openConnection();
BufferedReader in = null;
url = "";
in = new BufferedReader(new InputStreamReader(openConnection.getInputStream()));
String input = "";
if (in != null) {
while ((input = in.readLine()) != null) {
url = url + input + "\r\n";
}
in.close();
}
} catch (Exception ex) {
ex.printStackTrace();
}
return url;
}
public ArrayList<String> getURLs(String page) {
ArrayList<String> s = new ArrayList<String>();
while (page.toLowerCase().contains("<a href=\"http")) {
int i = page.toLowerCase().indexOf("href=\"http") + "href=\"".length();
if (i > -1) {
String s1 = page.substring(i, page.toLowerCase().indexOf("\"", i));
s.add(s1);
page = page.substring(i + "http".length());
}
}
return s;
}
public boolean validate(String email) {
Pattern pattern;
Matcher matcher;
final String EMAIL_PATTERN = "^[_A-Za-z0-9-]+(\\.[_A-Za-z0-9-]+)*" + "#[A-Za-z0-9]+(\\.[A-Za-z0-9]+)*(\\.[A-Za-z]{2,})$";
pattern = Pattern.compile(EMAIL_PATTERN);
matcher = pattern.matcher(email);
return matcher.matches();
}
public ArrayList<String> getAddresses(String page) {
ArrayList<String> s = new ArrayList<String>();
while (page.contains("#")) {
int i = page.indexOf("#");
if (i > -1) {
int beginning = page.lastIndexOf(" ", i);
if (beginning > -1) {
int ending = page.indexOf(" ", i);
if (ending > -1) {
String address = page.substring(beginning + 1, ending - 1);
address = address.toLowerCase();
if (address.startsWith("href=\"mailto:")) {
int b = address.indexOf(":") + 1;
address = address.substring(b);
int e = address.indexOf("\"");
if (e > -1) {
if (e > address.indexOf("#")) {
address = address.substring(0, address.indexOf("\""));
}
if (address.contains("?")) {
address = address.substring(0, address.indexOf("?"));
}
if (!address.contains("<") && !address.contains(">")) {
if (validate(address)) {
s.add(address);
}
}
} else {
int b2 = address.indexOf(">") + 1;
if (b2 > -1) {
if (b2 < address.indexOf("#")) {
address = address.substring(b2);
}
}
int e2 = address.indexOf("<");
if (e2 > -1) {
if (e2 > address.indexOf("#")) {
address = address.substring(0, e2);
}
}
if (!address.contains("<") && !address.contains(">")) {
if (validate(address)) {
s.add(address);
}
}
}
}
}
}
}
page = page.substring(i + 1);
}
return s;
}
public ArrayList<String> removeDuplicates(ArrayList<String> List) {
ArrayList<String> output = new ArrayList<String>();
for (int i = 0; i < List.size(); i++) {
boolean b = false;
for (int a = 0; a < List.size(); i++) {
if (List.get(i).toString().toLowerCase().equals(List.get(a).toString().toLowerCase())) {
b = true;
}
}
if (b == false) {
output.add(List.get(i));
}
}
return output;
}
}
This Program Was Made in AIDE on an android netbook.
It Crashes On Button Click. I was wondering what I Was doing wrong.
I tried before with runnables but it crashed then too. I'm new to
android development but I am fluent in Java. I noticed there are
alot of differences between android and Java.

Why can't I update my EditText in onPostExecute with Geocoder in the AsyncTask?

I am trying to reverse geocode inside an AsyncTask to get the address of the current location. I want to set the EditText to the address as default when starting the activity. My problem is I am unable to do this in onPostExecute(), however, I can do it in runOnUiThread() inside doInBackground(). Why is this?
AsyncTask:
protected String doInBackground(Void ...params) {
Geocoder geocoder = new Geocoder(AddSpot.this, Locale.getDefault());
List<Address> addresses = null;
try {
// Call the synchronous getFromLocation() method by passing in the lat/long values.
addresses = geocoder.getFromLocation(currentLat, currentLng, 1);
}
catch (IOException e)
{
e.printStackTrace();
}
if (addresses != null && addresses.size() > 0)
{
Address address = addresses.get(0);
// Format the first line of address (if available), city, and country name.
final String addressText = String.format("%s, %s, %s",
address.getMaxAddressLineIndex() > 0 ? address.getAddressLine(0) : "",
address.getLocality(),
address.getCountryName());
System.out.println(addressText);
return addressText;
}
return null;
}
protected void onPostExecute(String address) {
EditText addrField=(EditText)findViewById(R.id.addr);
addrField.setText(address);
}
That does not work. However, when I stick a runOnUiThread in it, it works:
if (addresses != null && addresses.size() > 0)
{
Address address = addresses.get(0);
// Format the first line of address (if available), city, and country name.
final String addressText = String.format("%s, %s, %s",
address.getMaxAddressLineIndex() > 0 ? address.getAddressLine(0) : "",
address.getLocality(),
address.getCountryName());
runOnUiThread(new Runnable()
{
#Override
public void run()
{
EditText addrField=(EditText)findViewById(R.id.addr);
addrField.setText(addressText);
}
});
System.out.println(addressText);
return addressText;
}
UPDATE
After some debugging it appears that onPostExecute is never called at all no matter what I do.
Things I have tried:
Log information inside onPostExecute: Does not appear
Remove the entire logic inside doInBackground so it's like this return "hello" : onPost still does not execute
You did not put #Override above onPostExecute. Also asynctask object must to be created inside UI thread.
EDIT: Your edittextis not updated, becauseit is consumedimidiatly after post execute is finished.
1) write EditText addrField; as class variable of activity class.
2) find reference to it in onCreate().
3) on your original onpostexecute should remain only addrField.setText(address);
there is my class, where textfields are updated from onPostexecute without any problems
public class AddToCheckActivity extends Activity {
// All static variables
private ProgressDialog pd = null;
// XML node keys
TextView active;
String addId = "";
JSONObject json = null;
ListView list;
String not_id, not_section, not_street, not_sqTotal, not_sqLiving,
not_sqKitchen, not_flat, not_floor, not_floors, not_text,
user_phone1, user_phone2, user_contact, not_region, not_district,
not_settle, not_price, not_photo, not_date, not_date_till, not_up,
not_premium, not_status, region_title, district_title,
settle_title, section_title, not_priceFor;
LinearLayout lin;
ImageView photo1;
ImageView photo2;
ImageView photo3;
Activity app;
ArrayList<String> photo_ids = new ArrayList<String>();
TextView address;
TextView date;
TextView date_till;
TextView description;
TextView district;
TextView flat;
TextView floor;
TextView floors;
TextView id;
TextView phone1;
TextView phone2;
TextView premium;
TextView region;
TextView section;
TextView settle;
TextView sqKitchen;
TextView sqLiving;
TextView sqTotal;
TextView uped;
TextView price;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.aadd_addtocheck);
app = this;
lin = (LinearLayout) findViewById(R.id.lin);
address = (TextView) findViewById(R.id.tv_atc_address);
date = (TextView) findViewById(R.id.tv_atc_date);
date_till = (TextView) findViewById(R.id.tv_atc_date_till);
description = (TextView) findViewById(R.id.tv_atc_description);
district = (TextView) findViewById(R.id.tv_atc_dstrict);
flat = (TextView) findViewById(R.id.tv_atc_flat);
floor = (TextView) findViewById(R.id.tv_atc_floor);
floors = (TextView) findViewById(R.id.tv_atc_floors);
id = (TextView) findViewById(R.id.tv_atc_id);
phone1 = (TextView) findViewById(R.id.tv_atc_phone1);
phone2 = (TextView) findViewById(R.id.tv_atc_phone2);
premium = (TextView) findViewById(R.id.tv_atc_premium);
region = (TextView) findViewById(R.id.tv_atc_region);
section = (TextView) findViewById(R.id.tv_atc_section);
settle = (TextView) findViewById(R.id.tv_atc_settle);
sqKitchen = (TextView) findViewById(R.id.tv_atc_sqKitchen);
sqLiving = (TextView) findViewById(R.id.tv_atc_sqLiving);
sqTotal = (TextView) findViewById(R.id.tv_atc_sqTotal);
uped = (TextView) findViewById(R.id.tv_atc_uped);
price = (TextView) findViewById(R.id.tv_atc_price);
Bundle ex = getIntent().getExtras();
Log.d("Gues: ", "1");
Button back_button = (Button) findViewById(R.id.back_btn);
back_button.setOnClickListener(new OnClickListener() {
public void onClick(View arg0) {
Intent i = new Intent(getApplicationContext(),
ChooserActivity.class);
startActivity(i);
finish();
}
});
pd = new ProgressDialog(app);
pd.setOwnerActivity(app);
pd.setTitle("Идет загрузка...");
pd.setCancelable(true);
if (ex != null) {
addId = ex.getString("add_id");
Log.d("Gues: ", "2");
not_id = not_priceFor = not_section = not_street = not_sqTotal = not_sqLiving = not_sqKitchen = not_flat = not_floor = not_floors = not_text = user_phone1 = user_phone2 = user_contact = not_region = not_district = not_settle = not_price = not_photo = not_date = not_date_till = not_up = not_premium = not_status = region_title = district_title = settle_title = section_title = "";
Log.d("Gues: ", "3");
GetAdd addvert = new GetAdd();
addvert.execute();
}
}
public void onClickBtnAtcDelete(View v) {
Thread t = new Thread(new Runnable() {
public void run() {
UserFunctions u = new UserFunctions();
u.deleteAdd(not_id);
}
});
t.start();
try {
t.join();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Intent i = new Intent(getApplicationContext(), MyAddActivity.class);
startActivity(i);
finish();
}
public void btnAtcEdit(View v) {
Intent i = new Intent(getApplicationContext(), AddSaveActivity.class);
final BitmapDrawable bitmapDrawable1 = (BitmapDrawable) photo1
.getDrawable();
final Bitmap yourBitmap1 = bitmapDrawable1.getBitmap();
ByteArrayOutputStream stream1 = new ByteArrayOutputStream();
yourBitmap1.compress(Bitmap.CompressFormat.PNG, 90, stream1);
byte[] imm1 = stream1.toByteArray();
final BitmapDrawable bitmapDrawable2 = (BitmapDrawable) photo2
.getDrawable();
final Bitmap yourBitmap2 = bitmapDrawable2.getBitmap();
ByteArrayOutputStream stream2 = new ByteArrayOutputStream();
yourBitmap2.compress(Bitmap.CompressFormat.PNG, 90, stream2);
byte[] imm2 = stream2.toByteArray();
final BitmapDrawable bitmapDrawable3 = (BitmapDrawable) photo3
.getDrawable();
final Bitmap yourBitmap3 = bitmapDrawable3.getBitmap();
ByteArrayOutputStream stream3 = new ByteArrayOutputStream();
yourBitmap3.compress(Bitmap.CompressFormat.PNG, 90, stream3);
byte[] imm3 = stream3.toByteArray();
i.putExtra("photo1", imm1);
i.putExtra("photo2", imm2);
i.putExtra("photo3", imm3);
i.putStringArrayListExtra("photo_ids", photo_ids);
i.putExtra("not_id", not_id);
i.putExtra("not_section", not_section);
i.putExtra("not_street", not_street);
i.putExtra("not_sqTotal", not_sqTotal);
i.putExtra("not_sqLiving", not_sqLiving);
i.putExtra("not_sqKitchen", not_sqKitchen);
i.putExtra("not_flat", not_flat);
i.putExtra("not_floor", not_floor);
i.putExtra("not_floors", not_floors);
i.putExtra("not_text", not_text);
i.putExtra("not_phone1", user_phone1);
i.putExtra("not_phone2", user_phone2);
i.putExtra("not_region", not_region);
i.putExtra("not_district", not_district);
i.putExtra("not_settle", not_settle);
i.putExtra("not_price", not_price);
i.putExtra("not_date", not_date);
i.putExtra("not_date_till", not_date_till);
i.putExtra("region_title", region_title);
i.putExtra("district_title", district_title);
i.putExtra("section_title", section_title);
i.putExtra("settle_title", settle_title);
i.putExtra("not_priceFor", not_priceFor);
startActivity(i);
}
public void onClickAtcGoToChooser(View v) {
Intent i = new Intent(getApplicationContext(), MyAddActivity.class);
startActivity(i);
finish();
}
class GetAdd extends AsyncTask<Integer, Void, JSONObject> {
// private ProgressDialog pd = null;
private int op = 0;
#Override
protected void onPreExecute() {
// pd = new ProgressDialog(app);
// pd.setOwnerActivity(app);
// pd.setTitle("Идет загрузка...");
// pd.setCancelable(true);
pd.show();
}
#Override
protected JSONObject doInBackground(Integer... params) {
// TODO Auto-generated method stub
UserFunctions u = new UserFunctions();
// json = u.getNewAdd(addId);
return u.getNewAdd(addId);
}
#Override
protected void onPostExecute(JSONObject result) {
super.onPostExecute(result);
pd.dismiss();
active = (TextView) findViewById(R.id.tv_atc_active);
photo1 = (ImageView) findViewById(R.id.imageP1);
photo2 = (ImageView) findViewById(R.id.imageP2);
photo3 = (ImageView) findViewById(R.id.imageP3);
ImageLoader imi = new ImageLoader(app.getApplicationContext());
if (result != null && result.has("not_id")) {
try {
Log.d("Gues: ",
"5_1 to status " + result.getString("not_status"));
// active.setText(json.getString("not_status")+"");
not_status = ("" + result.getString("not_status"));
not_region = ("" + result.getString("not_region"));
not_district = ("" + result.getString("not_district"));
not_settle = ("" + result.getString("not_settle"));
not_section = ("" + result.getString("not_section"));
not_street = (result.getString("not_street"));
not_date = (result.getString("not_date"));
not_price = (result.getString("not_price"));
not_date_till = (result.getString("not_date_till"));
not_text = (result.getString("not_text"));
district_title = (result.getString("district_title"));
not_flat = (result.getString("not_flat"));
not_floor = (result.getString("not_floor"));
not_floors = (result.getString("not_floors"));
not_id = (result.getString("not_id"));
user_phone1 = (result.getString("user_phone1"));
user_phone2 = (result.getString("user_phone2"));
not_premium = (result.getString("not_premium"));
region_title = (result.getString("region_title"));
section_title = (result.getString("section_title"));
settle_title = (result.getString("settle_title"));
not_sqKitchen = (result.getString("not_sqKitchen"));
not_sqTotal = (result.getString("not_sqTotal"));
not_sqLiving = (result.getString("not_sqLiving"));
not_up = (result.getString("not_up"));
LinearLayout l = (LinearLayout) findViewById(R.id.appDetail);
if (Integer.parseInt(not_section) == 1981
|| Integer.parseInt(not_section) == 1982) {
l.setVisibility(View.GONE);
}
not_priceFor = (result.getString("not_priceFor"));
String link1, link2, link3;
link1 = link2 = link3 = "";
JSONArray ar = result.getJSONArray("not_photos");
JSONArray pp = result.getJSONArray("photo_ids");
Log.d("ATC photo_ids", "-" + pp.length());
Log.d("ATC result", result.toString());
Log.d("ATC result pp", pp.toString());
Log.d("ATC result ppelement", pp.getString(0).toString());
for (int i = 0; i < pp.length(); i++) {
Log.d("ATC photo_ids pos", "-" + i);
Log.d("ATC result ppelement iter", pp.getString(i)
.toString());
photo_ids.add(pp.getString(i).toString());
}
// String[] ph = new String[3];
// for (int i =0; i< 3;i++){
// ph[i]=ar.getJSONObject(i).toString();
// }
imi.DisplayImage(ar.getString(0).toString(), photo1);
imi.DisplayImage(ar.getString(1).toString(), photo2);
imi.DisplayImage(ar.getString(2).toString(), photo3);
Log.d("Gues: ", "5_5");
runOnUiThread(new Runnable() {
#Override
public void run() {
}
});
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
if (Integer.parseInt(not_status) == 0) {
active.setText("Неактивно");
} else {
active.setText("Активно");
}
address.setText("Улица: " + not_street);
date.setText("Создано: " + not_date);
date_till.setText("Действительно до: " + not_date_till);
description.setText("Подробности объявления: " + "\n"
+ not_text);
district.setText("Город/поселок: " + district_title);
if (Integer.parseInt(not_section) == 1981
|| Integer.parseInt(not_section) == 1982) {
flat.setText("Машиномест: " + not_flat);
} else
flat.setText("Количество комнат: " + not_flat);
floor.setText("Этаж: " + not_floor);
floors.setText("Этажность: " + not_floors);
id.setText("ID: " + not_id + " ");
phone1.setText("Телефон: " + user_phone1);
phone2.setText("Телефон: " + user_phone2);
if (Integer.parseInt(not_premium) == 0) {
premium.setText("Обычное");
} else {
premium.setText(" Примиумное");
}
region.setText("Регион: " + region_title);
section.setText("В рубрике: " + section_title);
settle.setText("Район: " + settle_title);
sqKitchen.setText("Площадь кухни: " + not_sqKitchen);
sqTotal.setText("Общая площадь: " + not_sqTotal);
sqLiving.setText("Жилая площадь: " + not_sqLiving);
if (Integer.parseInt(not_up) == 0) {
uped.setText("");
} else {
uped.setText(" Поднятое ");
}
String priceT = "";
if (Integer.parseInt(not_priceFor) == 1)
priceT = "за все";
else if (Integer.parseInt(not_priceFor) == 2)
priceT = "за кв.м";
else if (Integer.parseInt(not_priceFor) == 3)
priceT = "за месяц";
else if (Integer.parseInt(not_priceFor) == 4)
priceT = "в сутки";
else if (Integer.parseInt(not_priceFor) == 5)
priceT = "в час";
else if (Integer.parseInt(not_priceFor) == 6)
priceT = "за кв.м./месяц";
else if (Integer.parseInt(not_priceFor) == 7)
priceT = "за сотку";
price.setText("Цена: " + not_price + " грн. " + priceT);
lin.setVisibility(View.VISIBLE);
} else {
error();
}
}
}
}
PS: t oavoid problems in future, don't put UI operations in any part of try{}

Categories

Resources