When the user hit the bottom of my listview, the second page is loaded and displayed. The problem is that, when it happens, the items of the first page are replaced with the ones of the second page. This video show the behaviour: https://www.ubris.design/video.mp4
and this is my code, inside the respomnse callback of my webservice:
try {
JSONObject obj = new JSONObject(result);
JSONObject response = obj.getJSONObject("response");
Integer count = Integer.parseInt(response.getString("count"));
//Toast.makeText(getApplicationContext(),count+"", Toast.LENGTH_LONG).show();
inputItems.clear();
for(int i = 0; i < count; i++){
JSONObject tmp = response.getJSONObject(i+"");
id = tmp.getString("id");
materia = tmp.getString("materia");
adsce = tmp.getString("adsce");
nomeCompleto = tmp.getString("nomeCompleto");
matricola = tmp.getString("matricola");
username = tmp.getString("username");
password = tmp.getString("password");
uni = tmp.getString("uni");
descrizione = tmp.getString("descrizione");
type = tmp.getString("type");
voto = tmp.getString("voto");
votanti = tmp.getString("votanti");
ts = tmp.getString("ts");
//url
siteTitle = tmp.getString("siteTitle");
siteDescription = tmp.getString("siteDescription");
siteImage = tmp.getString("siteImage");
address = tmp.getString("address");
//file
filename = tmp.getString("filename");
filesize = tmp.getString("filesize");
combinedSize = tmp.getString("combinedSize");
//Toast.makeText(getApplicationContext(), filename+address, Toast.LENGTH_LONG).show();
inputItems.add(new DTODocSelected(id, materia, adsce, nomeCompleto, matricola, null, null, uni, descrizione,type, voto, votanti, ts,
siteTitle, siteDescription, siteImage, address,
filename, filesize, combinedSize
));
}
} catch (Exception e){
Toast.makeText(getApplicationContext(), e.toString(), Toast.LENGTH_LONG).show();
e.printStackTrace();
}
if(inputItems.size() > 0){
if(page == 0){
adapter = new AdapterDocMateriaDocsSelect(getApplicationContext(),
R.id.activity_docs_doc_selected, inputItems);
listView.setAdapter(adapter);
listView.setSmoothScrollbarEnabled(true);
listView.setScrollingCacheEnabled(false);
listView.setDrawingCacheEnabled(false);
listView.destroyDrawingCache();
listView.buildDrawingCache(false);
listView.getDrawingCache(false);
double vv = Integer.valueOf(counterCC);
double pagineMax = Math.ceil( vv / 5);
int pagineMaxInt = (int) pagineMax;
if(page == (pagineMaxInt - 1)){
pagination = false;
Toast.makeText(getApplicationContext(), "pagination false", Toast.LENGTH_SHORT).show();
}
} else {
//Toast.makeText(getApplicationContext(), ""+inputItems.size(), Toast.LENGTH_SHORT).show();
double vv = Integer.valueOf(counterCC);
double pagineMax = Math.ceil( vv / 5);
int pagineMaxInt = (int) pagineMax;
if(page == (pagineMaxInt - 1)){
pagination = false;
Toast.makeText(getApplicationContext(), "pagination false", Toast.LENGTH_SHORT).show();
}
adapter.addAll(inputItems);
//inputItems.clear();
//listView.setSmoothScrollbarEnabled(true);
//listView.smoothScrollToPosition(page * 5);
}
} else {
pagination = false;
//Toast.makeText(getApplicationContext(), "zero", Toast.LENGTH_LONG).show();
}
to solve I just replaced adapter.addAll(inputItems); with adapter.notifyDataSetChanged(); and removed inputItems.clear();
Related
I having a problem update the Item in Recycler View.I will explain clearly about my problem.
I am using two Json URL's first Json URL can send the items to model class.
after completed this called the adapter, then update the second Json URL items with the adapter by using setter model class.
so that's why called adapter.notifyitemchanged, but only one time can updated items next time while looping doesn't update the items display empty for second time.
Code:
public void servicecallsingle(String list, final int pin) {
url = Constants.singleproducturl + list;
JsonObjectRequest request1 = new JsonObjectRequest(Request.Method.GET, url, null, new Response.Listener < JSONObject > () {
#Override
public void onResponse(JSONObject response) {
JSONObject response1 = response;
if (response1 != null) {
// int status=jsonObject.optInt("status");
String status = response1.optString("status");
if (status.equalsIgnoreCase("200")) { //check the status 200 or not
try {
productpath = response1.getString("productPath");
} catch (JSONException e) {
e.printStackTrace();
}
try {
JSONObject responses = response1.getJSONObject("response");
jsonarray = responses.getJSONArray(DATA);
if (jsonarray.length() > 0) {
// looping through json and adding to movies list
for (int i = 0; i < jsonarray.length(); i++) {
item = new CartItemoriginal();
JSONObject product = jsonarray.getJSONObject(i);
cartpid = product.getString("product_id");
cartproductname = product.getString("product_name");
cartaliasname = product.getString("product_alias");
cartprice = product.getString("mrp_price");
String sp = product.getString("selling_price");
String op = product.getString("offer_selling_price");
sellerid = product.getString("seller_id");
JSONArray pimg = product.getJSONArray("product_images");
JSONObject firstimg = pimg.getJSONObject(0);
cartimg = firstimg.getString("original_res");
String[] img2 = cartimg.split("\\.");
String imagone = productpath + sellerid + '/' + img2[0] + '(' + '2' + '0' + '0' + ')' + '.' + img2[1];
String Quantity = product.getString("product_max_add");
String minqty = product.getString("product_min_add");
int qty = Integer.parseInt(Quantity);
/*** calculation ***/
Long tsLong = System.currentTimeMillis() / 1000;
String ts = tsLong.toString();
int ts1 = Integer.parseInt(ts);
String startdate1 = product.getString("offer_selling_start_date");
String endate1 = product.getString("offer_selling_end_date");
if (("".equals(startdate1)) && ("".equals(endate1))) {
// Toast.makeText(getActivity(),"wrong statemnt",Toast.LENGTH_LONG).show();
if (cartprice.equalsIgnoreCase(sp)) {
double d = Double.parseDouble(cartprice);
int mrp = (int) d;
price = String.valueOf(mrp);
} else {
double s = Double.parseDouble(sp);
int sales = (int) s;
price = String.valueOf(sales);
}
} else {
int startdate = Integer.parseInt(startdate1);
int endate2 = Integer.parseInt(endate1);
if (ts1 > startdate && ts1 < endate2) {
double offer = Double.parseDouble(op);
int offers = (int) offer;
price = String.valueOf(offers);
} else {
if (cartprice.equalsIgnoreCase(sp)) {
double d = Double.parseDouble(cartprice);
int mrp = (int) d;
price = String.valueOf(mrp);
} else {
double s = Double.parseDouble(sp);
int sales = (int) s;
price = String.valueOf(sales);
}
}
}
item.setProductname(cartproductname);
item.setQty(1);
item.setProductimg(imagone);
item.setMaxquantity(Quantity);
item.setAliasname(cartaliasname);
item.setPrice(price);
item.setMinquantity(minqty);
item.setProductid(cartpid);
cart.add(item);
// cart.add(new CartItemoriginal(imagone,cartproductname,cartaliasname,1,Quantity,minqty,price,cartpid));
}
}
} catch (JSONException e) {
e.printStackTrace();
}
} // condtion check the status 200
else // this is if status falied in runtime
{
Toast.makeText(CartItems.this, "Status Failed in Banner Page check ur network connection", Toast.LENGTH_LONG).show();
}
// llm = new LinearLayoutManager(CartItems.this);
MainLinear.setVisibility(View.VISIBLE);
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();
}
String id = cartpid;
String selleid = sellerid;
final int pinnum = pin;
String pinurl = "http://192.168.0.33/sharpswebsite3/qcrest1.0/?type=pinCodeCheck&result=json&product_id=" + id + "&seller_id=" + selleid + "&pinCode=" + pinnum;
JsonObjectRequest request2 = new JsonObjectRequest(Request.Method.GET, pinurl, null, new Response.Listener < JSONObject > () {
#Override
public void onResponse(JSONObject responsesecond) {
JSONObject response2 = responsesecond;
// do something with response1 & response here...
if (response2 != null) {
// int status=jsonObject.optInt("status");
String status = response2.optString("status");
if (status.equalsIgnoreCase("200")) { //check the status 200 or not
try {
JSONObject responses = response2.getJSONObject("response");
jsonarray = responses.getJSONArray(DATA);
if (jsonarray.length() > 0) {
Log.i(String.valueOf(jsonarray.length()), "message");
// looping through json and adding to movies list
for (int j = 0; j < jsonarray.length(); j++) {
JSONObject product = jsonarray.getJSONObject(j);
process = product.getString("process");
Message = product.getString("message");
if (process.equalsIgnoreCase("success") && Message.equalsIgnoreCase("success")) {
cartdelivery = product.getString("delivery");
cartshippingcharge = product.getString("shipping_charge");
String pincode = product.getString("pincode");
/**************************calculation of shipping days**************************/
int day = Integer.parseInt(cartdelivery);
Calendar c = Calendar.getInstance();
String dayNumberSuffix = getDayNumberSuffix(day);
SimpleDateFormat sdf = new SimpleDateFormat(" MMM d'" + dayNumberSuffix + "', yyyy");
String currentDateandTime = sdf.format(new Date());
try {
c.setTime(sdf.parse(currentDateandTime));
} catch (ParseException e) {
e.printStackTrace();
}
c.add(Calendar.DATE, day);
Date resultdate = new Date(c.getTimeInMillis());
currentDateandTime = sdf.format(resultdate);
Log.d(String.valueOf(currentDateandTime), "shipping days");
cart.get(j).setDelivery("Standard delivery by" + " " + currentDateandTime);
cart.get(j).setShippincharge(cartshippingcharge);
cart.get(j).setSellername("richard feloboune");
cartadapter.notifyItemChanged(j);
cartadapter.notifyItemRangeChanged(j, cart.size());
} else {
// cart2.add(new Cartitemoringinaltwo("Seller doesn't deliver to this item to"+" "+ String.valueOf(pinnum)));
cart.get(j).setError("Seller doesn't deliver to this item to" + " " + String.valueOf(pinnum));
cartadapter.notifyItemChanged(j);
}
}
}
} catch (JSONException e) {
e.printStackTrace();
}
// stopping swipe refresh
// swipeRefreshLayout.setRefreshing(false);
} // condtion check the status 200
else // this is if status falied in runtime
{
Toast.makeText(CartItems.this, "Status Failed in Banner Page check ur network connection", Toast.LENGTH_LONG).show();
}
}
pincheck();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.i("onErrorResponse", error.toString());
}
});
AppController.getInstance().addToRequestQueue(request2);
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.i("onErrorResponse", error.toString());
}
});
AppController.getInstance().addToRequestQueue(request1);
}
Note: While looping first time can set the item in setter model class but second couldn't set the item to model class.
Anyone solve this problem glad to appreciate.
Thanks in advance
The problem is volley doesn't wait for the request to be completed. So as the first call is made within seconds other call will be also made. So, you need to create an interface which will be called when the first webservice is called, and than in interface call other webservice and than notifyDataSet.
public void servicecallsingle(String list, final int pin) {
url = Constants.singleproducturl + list;
JsonObjectRequest request1 = new JsonObjectRequest(Request.Method.GET, url, null, new Response.Listener < JSONObject > () {
#Override
public void onResponse(JSONObject response) {
JSONObject response1 = response;
if (response1 != null) {
// int status=jsonObject.optInt("status");
String status = response1.optString("status");
if (status.equalsIgnoreCase("200")) { //check the status 200 or not
try {
productpath = response1.getString("productPath");
} catch (JSONException e) {
e.printStackTrace();
}
parseJson(response1, new WebServiceCallBack{
public void getWebserviceCallBack(){
// Call another webservice here
String id = cartpid;
String selleid = sellerid;
final int pinnum = pin;
String pinurl = "http://192.168.0.33/sharpswebsite3/qcrest1.0/?type=pinCodeCheck&result=json&product_id=" + id + "&seller_id=" + selleid + "&pinCode=" + pinnum;
JsonObjectRequest request2 = new JsonObjectRequest(Request.Method.GET, pinurl, null, new Response.Listener < JSONObject > () {
#Override
public void onResponse(JSONObject responsesecond) {
JSONObject response2 = responsesecond;
// do something with response1 & response here...
if (response2 != null) {
// int status=jsonObject.optInt("status");
String status = response2.optString("status");
if (status.equalsIgnoreCase("200")) { //check the status 200 or not
try {
JSONObject responses = response2.getJSONObject("response");
jsonarray = responses.getJSONArray(DATA);
if (jsonarray.length() > 0) {
Log.i(String.valueOf(jsonarray.length()), "message");
// looping through json and adding to movies list
for (int j = 0; j < jsonarray.length(); j++) {
JSONObject product = jsonarray.getJSONObject(j);
process = product.getString("process");
Message = product.getString("message");
if (process.equalsIgnoreCase("success") && Message.equalsIgnoreCase("success")) {
cartdelivery = product.getString("delivery");
cartshippingcharge = product.getString("shipping_charge");
String pincode = product.getString("pincode");
/**************************calculation of shipping days**************************/
int day = Integer.parseInt(cartdelivery);
Calendar c = Calendar.getInstance();
String dayNumberSuffix = getDayNumberSuffix(day);
SimpleDateFormat sdf = new SimpleDateFormat(" MMM d'" + dayNumberSuffix + "', yyyy");
String currentDateandTime = sdf.format(new Date());
try {
c.setTime(sdf.parse(currentDateandTime));
} catch (ParseException e) {
e.printStackTrace();
}
c.add(Calendar.DATE, day);
Date resultdate = new Date(c.getTimeInMillis());
currentDateandTime = sdf.format(resultdate);
Log.d(String.valueOf(currentDateandTime), "shipping days");
cart.get(j).setDelivery("Standard delivery by" + " " + currentDateandTime);
cart.get(j).setShippincharge(cartshippingcharge);
cart.get(j).setSellername("richard feloboune");
cartadapter.notifyItemChanged(j);
cartadapter.notifyItemRangeChanged(j, cart.size());
} else {
// cart2.add(new Cartitemoringinaltwo("Seller doesn't deliver to this item to"+" "+ String.valueOf(pinnum)));
cart.get(j).setError("Seller doesn't deliver to this item to" + " " + String.valueOf(pinnum));
cartadapter.notifyItemChanged(j);
}
}
}
} catch (JSONException e) {
e.printStackTrace();
}
// stopping swipe refresh
// swipeRefreshLayout.setRefreshing(false);
} // condtion check the status 200
else // this is if status falied in runtime
{
Toast.makeText(CartItems.this, "Status Failed in Banner Page check ur network connection", Toast.LENGTH_LONG).show();
}
}
pincheck();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.i("onErrorResponse", error.toString());
}
});
AppController.getInstance().addToRequestQueue(request2);
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.i("onErrorResponse", error.toString());
}
});
AppController.getInstance().addToRequestQueue(request1);
});
}
} // condtion check the status 200
else // this is if status falied in runtime
{
Toast.makeText(CartItems.this, "Status Failed in Banner Page check ur network connection", Toast.LENGTH_LONG).show();
}
// llm = new LinearLayoutManager(CartItems.this);
MainLinear.setVisibility(View.VISIBLE);
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();
}
public void parseJson(JSONObject response1, WebServiceCallBack webserviceCallBack){
try {
JSONObject responses = response1.getJSONObject("response");
jsonarray = responses.getJSONArray(DATA);
if (jsonarray.length() > 0) {
// looping through json and adding to movies list
for (int i = 0; i < jsonarray.length(); i++) {
item = new CartItemoriginal();
JSONObject product = jsonarray.getJSONObject(i);
cartpid = product.getString("product_id");
cartproductname = product.getString("product_name");
cartaliasname = product.getString("product_alias");
cartprice = product.getString("mrp_price");
String sp = product.getString("selling_price");
String op = product.getString("offer_selling_price");
sellerid = product.getString("seller_id");
JSONArray pimg = product.getJSONArray("product_images");
JSONObject firstimg = pimg.getJSONObject(0);
cartimg = firstimg.getString("original_res");
String[] img2 = cartimg.split("\\.");
String imagone = productpath + sellerid + '/' + img2[0] + '(' + '2' + '0' + '0' + ')' + '.' + img2[1];
String Quantity = product.getString("product_max_add");
String minqty = product.getString("product_min_add");
int qty = Integer.parseInt(Quantity);
/*** calculation ***/
Long tsLong = System.currentTimeMillis() / 1000;
String ts = tsLong.toString();
int ts1 = Integer.parseInt(ts);
String startdate1 = product.getString("offer_selling_start_date");
String endate1 = product.getString("offer_selling_end_date");
if (("".equals(startdate1)) && ("".equals(endate1))) {
// Toast.makeText(getActivity(),"wrong statemnt",Toast.LENGTH_LONG).show();
if (cartprice.equalsIgnoreCase(sp)) {
double d = Double.parseDouble(cartprice);
int mrp = (int) d;
price = String.valueOf(mrp);
} else {
double s = Double.parseDouble(sp);
int sales = (int) s;
price = String.valueOf(sales);
}
} else {
int startdate = Integer.parseInt(startdate1);
int endate2 = Integer.parseInt(endate1);
if (ts1 > startdate && ts1 < endate2) {
double offer = Double.parseDouble(op);
int offers = (int) offer;
price = String.valueOf(offers);
} else {
if (cartprice.equalsIgnoreCase(sp)) {
double d = Double.parseDouble(cartprice);
int mrp = (int) d;
price = String.valueOf(mrp);
} else {
double s = Double.parseDouble(sp);
int sales = (int) s;
price = String.valueOf(sales);
}
}
}
item.setProductname(cartproductname);
item.setQty(1);
item.setProductimg(imagone);
item.setMaxquantity(Quantity);
item.setAliasname(cartaliasname);
item.setPrice(price);
item.setMinquantity(minqty);
item.setProductid(cartpid);
cart.add(item);
// cart.add(new CartItemoriginal(imagone,cartproductname,cartaliasname,1,Quantity,minqty,price,cartpid));
}
}
} catch (JSONException e) {
e.printStackTrace();}
webserviceCallBack.getWebserviceCallBack();
}
public interface WebServiceCallBack{
public void getWebserviceCallBack()
}
I am creating here a dynamic layout. I have one parent layout in which I am adding all the dynamic created views. Now on click of particular view I need position.
According to that position I have to send JsonObject which contain this view in Android. Here I am not able to get exact position of view.
This is my code:
int len = result.length();
View addView;
if (!(len == 0)) {
finalResult.clear();
for (int i = 0; i <= len; i++) {
try {
finalResult.add(result.getJSONObject(i));
} catch (JSONException e) {
e.printStackTrace();
}
}
for (int i = 0; i < result.length(); i++) {
JSONObject obj = result.getJSONObject(i);
if (i == 0) {
addView = mInflater.inflate(R.layout.sightseeing_firstview, null);
image = (ImageView) addView.findViewById(R.id.imagesightseeing_first);
textview = (TextView) addView.findViewById(R.id.textView1);
llfirst = (LinearLayout) addView.findViewById(R.id.llfirstview);
llayout.addView(addView);
String category1 = finalResult.get(i).getString("CategoryName");
imageurl1 = finalResult.get(i).getString("ImageUrl");
((BaseActivity) SightseeingToursActivity.this).imageLoader.displayImage(imageurl1, image,
Common.optionsSmall);
textview.setText(category1);
} else if (i % 5 == 0) {
addView = mInflater.inflate(R.layout.sightseeing_firstview, null);
images = (ImageView) addView.findViewById(R.id.imagesightseeing_first);
textview = (TextView) addView.findViewById(R.id.textView1);
llfirst = (LinearLayout) addView.findViewById(R.id.llfirstview);
llayout.addView(addView);
String category1 = finalResult.get(i).getString("CategoryName");
imageurlss = finalResult.get(i).getString("ImageUrl");
((BaseActivity) SightseeingToursActivity.this).imageLoader.displayImage(imageurlss, images,
Common.optionsSmall);
textview.setText(category1);
} else {
addView = mInflater.inflate(R.layout.sightseeing_secondview, null);
iv = (ImageView) addView.findViewById(R.id.secondimagesightseeing_second);
tv = (TextView) addView.findViewById(R.id.textView2);
llsecond = (LinearLayout) addView.findViewById(R.id.llsecondview);
String category2 = finalResult.get(i).getString("CategoryName");
imageurl2 = finalResult.get(i).getString("ImageUrl");
((BaseActivity) SightseeingToursActivity.this).imageLoader.displayImage(imageurl2, iv,
Common.optionsSmall);
tv.setText(category2);
if (result.length() > i + 1) {
i++;
ivview = (ImageView) addView.findViewById(R.id.secondimagesightseeing_third);
text = (TextView) addView.findViewById(R.id.textView3);
llthird = (LinearLayout) addView.findViewById(R.id.llthirdview);
String category3 = finalResult.get(i).getString("CategoryName");
imageurl3 = finalResult.get(i).getString("ImageUrl");
((BaseActivity) SightseeingToursActivity.this).imageLoader.displayImage(imageurl3, ivview,
Common.optionsSmall);
text.setText(category3);
}
llayout.addView(addView);
}
position = llayout.indexOfChild(addView);
addView.setTag(position);
addView.setOnClickListener(this);
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
#Override
public void onClick(View v) {
position = (Integer) v.getTag();
Toast.makeText(SightseeingToursActivity.this, "Position" + position, Toast.LENGTH_SHORT).show();
try {
Intent in = new Intent(SightseeingToursActivity.this, sightseeing_list.class);
in.putExtra("TourList", result.getJSONObject(position).toString());
startActivity(in);
} catch (Exception e) {
}
}
ViewGroup parent;
int position;
for(int i = 0; i < parent.getChildCount(); ++i) {
int currentViewId = parent.getChildAt(i).getId();
if(currentViewId == wantendViewId) {
position = i;
}
}
try this
here is my code:
public class TrainingActivity extends Activity {
private EditText etIn1, etIn2, etDesired;
private TextView prevInput;
int W[][] = new int[2][];
int X[][] = new int[30][];
int w0=0, w1=0, w2=0, p=1, sum=0, clicks=0;
private Button nxtData;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.training_activity);
View backgroundImage = findViewById(R.id.background);
Drawable background = backgroundImage.getBackground();
background.setAlpha(40);
etIn1= (EditText) findViewById(R.id.etInput1);
etIn2 = (EditText) findViewById(R.id.etInput2);
etDesired = (EditText) findViewById(R.id.etDesired);
prevInput = (TextView) findViewById(R.id.prevInput);
nxtData = (Button) findViewById(R.id.nextData);
nxtData.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
int sum = 0;
++clicks;
int intetIn1 = Integer.parseInt(etIn1.getText().toString());
int intetIn2 = Integer.parseInt(etIn2.getText().toString());
int intetDesired = Integer.parseInt(etDesired.getText().toString());
X[clicks-1] = new int[] {intetIn1, intetIn2, 1};
prevInput.setText("Last Inputs: (" + intetIn1 + ", " + intetIn2 +
", " + intetDesired + ")");
if(clicks == 1) {
if(intetDesired == 1) {
W[0] = new int[] {intetIn1, intetIn2, 1};
W[1] = W[0];
} else if(intetDesired == (-1)){
W[0] = new int[] {-intetIn1, -intetIn2, -1};
W[1] = W[0];
}
} else if(clicks > 1) {
for(int i=0; i<3; i++){
sum = sum + W[clicks-1][i] * X[clicks-1][i];
} if(sum>0 && intetDesired==1) {
W[clicks] = W[clicks-1];
} else if(sum<0 && intetDesired==(-1)) {
W[clicks] = W[clicks-1];
} else if(sum<=0 && intetDesired==1) {
for(int i=0; i<3; i++) {
W[clicks][i] = W[clicks-1][i] + X[clicks-1][i];
}
} else if(sum>=0 && intetDesired==(-1)) {
for(int i=0; i<3; i++) {
W[clicks][i] = W[clicks-1][i] - X[clicks-1][i];
}
}
}
Toast.makeText(getApplicationContext(), "" + clicks,
Toast.LENGTH_SHORT).show();
System.out.println(X[0][0]);
etIn1.setText("");
etIn2.setText("");
etDesired.setText("");
}
});
}}
and here is the Exception:
java.lang.ArrayIndexOutOfBoundsException: length=2; index=2
the clicks is the number of times that user click the button. at first it's ok but when i try and add some more inputs it crashes. can you tell why this is happening?
index of array is always less than length as index starts form 0 whereas length from 1 therefore X[clicks-1] is causing the problem
What is the initial value of click variable.
Can you post more code related. And for the first time if click is 0 then
X[clicks-1] = new int[] {intetIn1, intetIn2, 1};
this says you are store these value at click-1 th position which is not even initialized.. so
int X[] = new int[]{intetIn1, intetIn2, 1};
would be better.
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{}
I can't understand what is wrong in my code . I am getting error in myAddressUniqueness. don't know why.Before i have tried it with string data type but got the same error. It is saying java.null exception.
ArrayList<String> myAddressUniqueness = null;
String name = "hello";
if (indexBody < 0 || !cursor.moveToFirst())
return;
smsList.clear();
do {
// int cursorPostion = cursor.getPosition();
String address;
String msgStr = cursor.getString(indexBody);
String senderNumber = cursor.getString(indexAddr);
Log.d("Name : ", senderNumber);
// String name = cursor.getString(cursor
// .getColumnIndex(PhoneLookup.DISPLAY_NAME));
// Log.d("Name : ",name);
if (name != null) {
address = name;
} else {
address = senderNumber;
}
Log.d("Address: ", address);
flag = 1;
//Log.e("Number: ", addressUniqueness.length + "");
for (j = 0; j < myAddressUniqueness.size(); j++) {
if (myAddressUniqueness.contains(address)) {
flag = 0;
break;
}
}
if (flag == 1) {
myAddressUniqueness.add(new String(address));
i++;
String str = "Sender: " + address + "\n";
smsList.add(str);
}
// TODO Auto-generated catch block
} while (cursor.moveToNext());
Change your declaration to
ArrayList<String> myAddressUniqueness = new ArrayList<String>();
You have it initialized to null. This will instantiate it then you can add data to it.
You should instantiate myAddressUniqueness by myAddressUniqueness = new ArrayList<String>() before using it.