I have a code, that should display each item in bank a different image, and if it cant find one: display a default one.
I have got everything to work, except the problem is that it does not display the drawables. How can i fix it?
My code:
public class BankViewFragment extends OSRSFragment {
private static final String TAG = "BankViewFragment";
private static Account account;
private ListView lv;
Handler handler;
ArrayList<HashMap<String, String>> ItemList;
public static BankViewFragment newInstance(final Account account) {
BankViewFragment fragment = new BankViewFragment();
Bundle b = new Bundle();
fragment.setArguments(b);
return fragment;
}
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
super.onCreateView(inflater, container, savedInstanceState);
View view = inflater.inflate(R.layout.bank_view, null);
ItemList = new ArrayList<>();
new GetItems().execute();
lv = view.findViewById(R.id.list);
handler = new Handler(Looper.getMainLooper());
return view;
}
public static int getResId(String resourceName, Class<?> c) {
try {
Field idField = c.getDeclaredField(resourceName);
return idField.getInt(idField);
} catch (Exception e) {
throw new RuntimeException("No resource ID found for: "
+ resourceName + " / " + c, e);
}
}
private class GetItems extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected Void doInBackground(Void... arg0) {
HttpHandler sh = new HttpHandler();
SharedPreferences sharedpreferences = getContext().getSharedPreferences("minescape", Context.MODE_PRIVATE);
String nikas = sharedpreferences.getString("bankname", "null");
String url = "https://api.minesca.pe/game/classic/stats?username=" + nikas;
String jsonStr = sh.makeServiceCall(url);
Log.e(TAG, "NIKAS: " + nikas);
Log.e(TAG, "ACCOUNT: " + account);
Log.e(TAG, "Response from url: " + jsonStr);
if (jsonStr != null) {
try {
JSONObject jsonObj = new JSONObject(jsonStr);
JSONObject items = jsonObj.getJSONObject("bank");
Iterator keys = items.keys();
while(keys.hasNext()) {
String dynamicKey = (String)keys.next();
JSONObject line = items.getJSONObject(dynamicKey);
String item = line.getString("item");
//Integer image = getResId(item, Drawable.class);
final Integer image = getResources().getIdentifier(item, "drawable", getActivity().getPackageName());
String amount = line.getString("amount");
Log.e(TAG, "DAIKTAS: " + item);
Log.e(TAG, "KIEKIS: " + amount);
HashMap<String, String> contact = new HashMap<>();
String itembank = item.replaceAll("i_", "");
String itembanks = itembank.replaceAll("_", " ");
contact.put("name", itembanks);
contact.put("email", amount);
LayoutInflater inflater = LayoutInflater.from(getContext());
View view = inflater.inflate(R.layout.list_item, null);
// lv = view.findViewById(R.id.list);
// iv = (ImageView) view.findViewById(R.id.logo);
final ImageView ims = (ImageView) view.findViewById(R.id.logo);
handler.post(new Runnable() {
public void run() {
if(image != null) {
if(image == 0) {
ims.setImageResource(R.drawable.i_noted);
Log.e(TAG, "rokas?: " + image);
} else {
Log.e(TAG, "drawable ID ID: " + image);
ims.setImageResource(image);
}
} else {
Log.e(TAG, "null?: " + image);
}
}
});
ItemList.add(contact);
}
} catch (final JSONException e) {
Log.e(TAG, "Json parsing error: " + e.getMessage());
new Runnable() {
#Override
public void run() {
Toast.makeText(getContext(),
"Json parsing error: " + e.getMessage(),
Toast.LENGTH_LONG).show();
}
};
}
} else {
Log.e(TAG, "Couldn't get json from server.");
new Runnable() {
#Override
public void run() {
Toast.makeText(getContext(),
"Couldn't get json from server!",
Toast.LENGTH_LONG).show();
}
};
}
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
ListAdapter adapter = new SimpleAdapter(getContext(), ItemList,
R.layout.list_item, new String[]{ "email","name"},
new int[]{R.id.email, R.id.name});
lv.setAdapter(adapter);
}
}
}
Logcat keeps messaging me this:
02-08 14:11:12.331 17584-17584/com.infonuascape.osrshelper W/Resources: Converting to string: TypedValue{t=0x5/d=0x601 a=1 r=0x10500d7}
You should choose right setter:
imageView.setImageDrawable(drawable) - to set drawable which you can get from
resources using getResource().getDrawable(R.drawable.drawable_id).
imageView.setImageResource(id) - to set image using resources id.
imageView.setImageBitmap(bitmap) - to set bitmap which you can create from drawable using:Bitmap bitmap = BitmapFactory.decodeResource(this.getResources(), R.drawable.drawable_id).
And if you are using getResources().getIdentifier(...); I offer you to use:
int imageResource = getResources().getIdentifier(item, "drawable", getActivity().getPackageName());
imageview= (ImageView)findViewById(R.id.imageView);
Drawable drawable = getResources().getDrawable(imageResource);
imageView.setImageDrawable(drawable );
Something like this...
Related
I am passing a JSON Array/object through and Intent.putExtra into a new activity where I want to use certain strings inside that array. I want to know how to link to the JSON being passed through and how I can access the String Extras??
{
#Override
public void onBindViewHolder(final CompanyAdapter.CompanyViewHolder
holder, final int position) {
//CompanyItem currentItem = companyItem.get(position);
//
//holder.mtitleText.setText(currentItem.getmCompanyTitle());
//holder.mnumberText.setText(currentItem.getmCompanyDescription());
//holder.mNodeText.setText(currentItem.getmNodeCount());
Log.d(TAG, "currentItemNode: " + position);
holder.mButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Log.d(TAG, "Clicked: " + position);
Object dataSet = null;
try {
dataSet = companyItem.get(position);
} catch (JSONException e) {
e.printStackTrace();
}
Log.d(TAG, "TEST: " + String.valueOf(dataSet));
Intent intent = new Intent(view.getContext(),
NodeDrawActivity.class);
intent.putExtra("jsonObject", dataSet.toString());
view.getContext().startActivity(intent);
Log.d(TAG, "TEST2: " + dataSet);
}
});
try{
holder.mtitleText.setText(companyItem.getJSONObject(position)
.getString("title"));
holder.mnumberText.setText
(companyItem.getJSONObject(position).getString("description"));
//holder.mNodeText.setText
(companyItem.getJSONObject(position).getString("company_status"));
Log.d(TAG, "onBindViewHolder: " + companyItem);
}catch (JSONException e){
e.printStackTrace();
}
}
#Override
public int getItemCount() {
Log.d(TAG, "getItemCount:");
return companyItem.length();
}
}
----------------------------New Activity On Create---------------------
{
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.node_activity);
mTitleText = findViewById(R.id.comanyName);
mDescriptionText = findViewById(R.id.descTitle);
mOfficerText = findViewById(R.id.officerText);
mAppCount = findViewById(R.id.appCount);
Intent intent = getIntent();
//intent.putExtra("jsonObject", companyData.toString());
String companyName = intent.getStringExtra("jsonObject");
String companyDescription = intent.getStringExtra("description");
Log.d(TAG, "companyDescription: " + companyDescription);
Log.d(TAG, "companyData: " + companyName);
// Object companyData = null;
//
// try {
// companyData = companyItem.get();
// } catch (JSONException e) {
// e.printStackTrace();
// }
//mTitleText.getText(companyItem.getJSONObject().getString(mtitleText);
//
mTitleText.setText
(companyItem.getJSONObject(position).getString("title"));
//
mnumberText.setText
companyItem.getJSONObject(position).getString("description"));
//
holder.mNodeText.setText(companyItem.getJSONObject(position).getString
("com
pany_status"));
Log.d(TAG, "onBindViewHolder: " + companyItem);
}
I want to receive the Title name and description as well as position from the other activity intent
You need to deserialise your object 1st in your second activity With Gson.
String dataSet = intent.getStringExtra("jsonObject");
Gson gsonData = new Gson();
Object data = gsonData.fromJson(dataSet, Object.class);
String companyName = data.getJSONObject(position)
.getString("title"));
String companyDescription = data.getJSONObject(position).getString("description"));
Something along those lines to get your JSON data out of your original object because right now its still just a string.
I'm trying to execute a class(GetDirecoes, which is in the MapsActivity) from another activity (DetailsActivity), the idea is, when I click in the floating action button (DetailsActivity) I execute that class (GetDirecoes) and then close my current activity (DetailsActivity), when I close this activity it will automatically open my parent activity (MapsActivity) which is where the method GetDirecoes is.
I'm trying to execute the method with this:
new MapsActivity.GetDirecoes().execute(latRepr, lngRepr);
But it doesn't work giving me the error:
MapsActivity' is not an enclosing class
The correction that android studio offers me is to make GetDirecoes static, but I can't do that because if I do it the entire class breaks, here's the GetDirecoes class:
public class GetDirecoes extends AsyncTask<String, Void, Void> implements Serializable {
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(MapsActivity.this);
pDialog.setMessage("Aguarde...");
pDialog.setCancelable(false);
pDialog.show();
}
#Override
protected Void doInBackground(String... params) {
HttpHandler sh = new HttpHandler();
txtDistanciaTotal = (TextView) findViewById(R.id.txtDistanciaTotal);
txtDuracaoTotal = (TextView) findViewById(R.id.txtDuracaoTotal);
instrucoes = (TextView) findViewById(R.id.Instrucoes);
String url1 = "https://maps.googleapis.com/maps/api/directions/json?origin=";
String url2 = "&destination=";
String url3 = "&key=AIzaSyBh6tmMrC6QaHMJewFGvGc8xOjc0WMajxQ&language=pt";
String latRepr = params[0];
String lngRepr = params[1];
final String jsonStr = sh.makeServiceCall(url1 + mylatitude + "," + mylongitude + url2 + latRepr + "," + lngRepr + url3);
Log.e(TAG, "Link: " + url1 + mylatitude + "," + mylongitude + url2 + latRepr + "," + lngRepr + url3);
Log.e(TAG, "Resposta do URL: " + jsonStr);
if (jsonStr != null) {
try {
JSONObject root = new JSONObject(jsonStr);
JSONArray routes = root.optJSONArray("routes");
if (routes != null) {
JSONObject singleRout = (JSONObject) routes.get(0);
JSONArray legs = (JSONArray) singleRout.get("legs");
if (legs != null) {
JSONObject singleLeg = (JSONObject) legs.get(0);
//Distancia total
JSONObject distanceT = (JSONObject) singleLeg.get("distance");
if (distanceT != null) {
distT = distanceT.getString("text");
}
//Duracao Total
JSONObject durationT = (JSONObject) singleLeg.get("duration");
if (durationT != null) {
duraT = durationT.getString("text");
}
JSONArray steps = (JSONArray) singleLeg.get("steps");
if (steps != null) {
for (int j = 0; j < steps.length(); j++) {
JSONObject singleStep = (JSONObject) steps.get(j);
HashMap<String, String> direcao = new HashMap<>();
JSONObject distance = (JSONObject) singleStep.get("distance");
//Distancia
if (distance != null) {
String dist = distance.getString("text");
direcao.put("textDi", dist);
}
//Duraçao
JSONObject duration = (JSONObject) singleStep.get("duration");
if (duration != null) {
String dura = duration.getString("text");
direcao.put("textDu", dura);
}
//Polylines
JSONObject singlePolyline = (JSONObject) singleStep.get("polyline");
if (singlePolyline != null) {
String points = singlePolyline.getString("points");
Map<String, String> caminho = new HashMap<>();
caminho.put("points", points);
listaPolylines.add((HashMap<String, String>) caminho);
}
//Instruções
String html = singleStep.getString("html_instructions");
direcao.put("html_instructions2", html);
listaDirecoes.add(direcao);
}
}
}
}
} catch (final JSONException e) {
Log.e(TAG, "ERROR: " + e.getMessage());
runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(getApplicationContext(), "ERROR: " + e.getMessage(), Toast.LENGTH_LONG).show();
}
});
}
} else {
Log.e(TAG, "ERROR");
runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(getApplicationContext(), "Verifique a sua ligação à internet", Toast.LENGTH_LONG).show();
}
});
}
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
final ListView list = (ListView) (MapsActivity.this).findViewById(R.id.listaDirecoes);
ListAdapter adapter = new SimpleAdapter(
(MapsActivity.this),
listaDirecoes,
R.layout.list_item_direcoes,
new String[]{"html_instructions2", "textDi", "textDu"},
new int[]{R.id.Instrucoes, R.id.txtDistancia, R.id.txtDuraçao});
list.setAdapter(adapter);
txtDuracaoTotal.setText(duraT);
txtDistanciaTotal.setText(distT);
fazerCaminho(listaPolylines);
if (pDialog.isShowing()) {
pDialog.dismiss();
}
bottom_sheet.setOnTouchListener(new View.OnTouchListener() {
public boolean onTouch(View v, MotionEvent event) {
Log.v(TAG, "Parent Touch");
findViewById(R.id.listaDirecoes).getParent().requestDisallowInterceptTouchEvent(false);
return false;
}
});
listaDirecoesChild.setOnTouchListener(new View.OnTouchListener() {
public boolean onTouch(View v, MotionEvent event) {
Log.v(TAG, "CHILD TOUCH");
// Disallow the touch request for parent scroll on touch of child view
v.getParent().requestDisallowInterceptTouchEvent(true);
return false;
}
});
}
}
you can go through Call a Class From another class
private Activity activity;
you should initialize, activity
From another class, call it as :
((DetailsActivity) activity).refreshList(latRepr, lngRepr);
Now in, DetailsActivity.class you can do as,
public void refreshList(String latRepr, String lngRepr) {
new GetDirecoes().execute(latRepr, lngRepr);
}
I am not able to find any appropriate solution for below issue. I am using AsyncTask app sends request to server and it returns the JSON array as response, in postExecute method I parsed it, and problem is when I try to set the parsed data to TextView, textview not showing data. I am sure that server returned some data, and this data was parsed in postExecute and saved in global variables. TextViews also was declared as global variables, and defined in OnCreate method. thanks in advance!
Please check Code mentioned below:
public class CompanyData extends AppCompatActivity implements View.OnClickListener {
Button cComments;
String ssid,bin;
String extra, extra1;
TextView compData1, compData2, compData3, compData4, compData5, compData6, compTitle;
String title, kod_okpo, address, reg_date, fio, kod_oked, ovd ;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_company_data);
cComments = (Button) findViewById(R.id.cComment);
cComments.setOnClickListener(this);
Bundle extras = getIntent().getExtras();
if (extras != null) {
extra = extras.getString("bin");
extra1 = extras.getString("ssid");
send_company_req(extra1, extra);
}
compTitle = (TextView) findViewById(R.id.companyTitle);
compData1 = (TextView) findViewById(R.id.compData1);
compData2 = (TextView) findViewById(R.id.compData2);
compData3 = (TextView) findViewById(R.id.compData3);
compData4 = (TextView) findViewById(R.id.compData4);
compData5 = (TextView) findViewById(R.id.compData5);
compData6 = (TextView) findViewById(R.id.compData6);
//Toast.makeText(this,"LOOOL" + title+bin+kod_okpo+address+reg_date+fio+kod_oked+ovd, Toast.LENGTH_SHORT).show();
}
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.cComment:
Intent companyData = new Intent(CompanyData.this, Comments.class);
companyData.putExtra("bin", bin);
companyData.putExtra("ssid", ssid);
startActivity(companyData);
startActivity(new Intent(this, Comments.class));
break;
}
}
private void send_company_req(final String ssid, final String searchData) {
class GetJSON extends AsyncTask<String, String, String> {
ProgressDialog loading;
String rStr;
#Override
protected void onPreExecute() {
super.onPreExecute();
loading = ProgressDialog.show(CompanyData.this, "Request...", null, true, true);
}
#Override
protected String doInBackground(String... params) {
String token = params[0];
String fi = params[1];
String uri = Quickstart.URL + "/car/info";
String param = null;
try {
param = "ssid=" + URLEncoder.encode(token, "UTF-8") +
"&bin=" + URLEncoder.encode(fi, "UTF-8") + "&dev=android";
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
try {
URL url = new URL(uri);
HttpURLConnection con = (HttpURLConnection) url.openConnection();
con.setDoOutput(true);
con.setRequestMethod("POST");
con.setFixedLengthStreamingMode(param.getBytes().length);
con.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
con.setRequestProperty("Authorization", "Bearer " + token);
PrintWriter out = new PrintWriter(con.getOutputStream());
out.print(param);
out.close();
String response = "";
Scanner inStream = new Scanner(con.getInputStream());
while (inStream.hasNextLine()) {
response += (inStream.nextLine());
}
return response;
} catch (Exception e) {
return null;
}
}
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
loading.dismiss();
//Toast.makeText(CompanyData.this, s, Toast.LENGTH_LONG).show();
JSONArray jsonArrayComp;
try {
jsonArrayComp = new JSONArray(s.trim());
JSONObject jsonObjectComp = jsonArrayComp.getJSONObject(0);
try {
title = jsonObjectComp.getString("title");
kod_okpo = jsonObjectComp.getString("kod_okpo");
address = jsonObjectComp.getString("address");
reg_date = jsonObjectComp.getString("reg_date");
fio = jsonObjectComp.getString("fio");
kod_oked = jsonObjectComp.getString("kod_1_oked");
ovd = jsonObjectComp.getString("vidd");
Toast.makeText(CompanyData.this,"LOOOL" + title+bin+kod_okpo+address+reg_date+fio+kod_oked+ovd, Toast.LENGTH_LONG).show();
} catch (Exception ee) {
}
} catch (Exception e) {
//Toast.makeText(CompanyData.this, "Упс,:( что то пошло не так, попробуйте еще раз пожалуйста.", Toast.LENGTH_SHORT).show();
}
compTitle.setText(title);
compData1.setText(bin);
compData2.setText(kod_okpo);
compData3.setText(address);
compData4.setText(reg_date);
compData5.setText(fio);
compData6.setText(kod_oked + " - " + ovd);
}
}
GetJSON gj = new GetJSON();
gj.execute(ssid, searchData);
}
}
The problem is that whenever the user go to the third fragment then coming back to the first one, all the data in the first fragment will be gone.
the Data will parsed from a web service, using AsyncTask within the fragment
this my onCreate() method
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
mParam1 = getArguments().getString(ARG_PARAM1);
mParam2 = getArguments().getString(ARG_PARAM2);
}
int radius = 4;
double latitude = 51.3674718208489;
double longtitude = -0.119329656538836;
Boolean loyal = false;
int mer = 1;
try {
parameters.put(ConstantKeys.SEARCH_NAME, searchname);
parameters.put(ConstantKeys.LOYALTY, isLoyalty);
Log.d(CommunityFragment.class.getSimpleName(), parameters.toString());
} catch (JSONException e) {
e.printStackTrace();
}
FindOfferField();
}
this is my onCreateView() method
public View onCreateView(LayoutInflater inflater,
ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.community_fragment, container, false);
return rootView;
}
and this is my AsynTask()
public void FindOfferField() {
RegisterRequest request = new RegisterRequest(getActivity());
SharedPreferences userpass = getActivity().getSharedPreferences("USERPASS", 0);
String email = userpass.getString("username", null);
String password = userpass.getString("password", null);
Log.d(CommunityFragment.class.getSimpleName(), "Email:" + email + " Password:" + password);
request.getToken(email, password, new ApiRequestListener() {
#Override
public void onSuccess(Object object) {
(new FindOfferTask() {
#Override
protected void onPostExecute(JSONObject data) {
super.onPostExecute(data);
try {
if (data.getString(ConstantKeys.RESULT).equals("OK")) {
array = data.getJSONArray(ConstantKeys.RESULTS);
RowItem items;
rowItem = new ArrayList<RowItem>();
for (int i = 0; i < array.length(); i++) {
final JSONObject list = array.getJSONObject(i);
items = new RowItem();
int id = Integer.parseInt(offerList.getString("Id"));
byID = id;
Log.d("AnotherID", String.valueOf(byID));
Boolean isCommunity = offerList.getBoolean(ConstantKeys.IS_COMMUNITY);
items.setId(list.getInt("Id"));
items.setMerchantid(list.getInt(ConstantKeys.MERCHANTID));
items.setDescription(list.getString(ConstantKeys.DESCRIPTION));
items.setDateEnd(list.getString(ConstantKeys.DATE).replace("T00:00:00", ""));
items.setTokensFor(list.getString(ConstantKeys.FOR));
if (!offerList.isNull("ImageId")) {
int bitmapImageID = offerList.getInt("ImageId");
Log.d("BITMAPHAHA", String.valueOf(bitmapImageID));
items.setImageId(bitmapImageID);
}
rowItem.add(items);
listView = (ListView) getView().findViewById(R.id.listViewCommunity);
adapter = new CustomListAdapter(getActivity(), rowItem);
adapter.notifyDataSetChanged();
listView.setAdapter(adapter);
getEndTask = new RowItemLoyalty();
getTask = new RowItem();
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
boolean isCommunity = false;
try {
isCommunity = offerList.getBoolean(ConstantKeys.IS_COMMUNITY);
} catch (JSONException e) {
e.printStackTrace();
}
int ID = rowItem.get(position).getId();
int merID = rowItem.get(position).getMerchantid();
Intent intent = new Intent(getActivity(), CustomerPromotion.class);
getEndTask.endTask();
getTask.endTask();
intent.putExtra("ID", ID);
intent.putExtra("MERCHANT", merID);
intent.putExtra("BOOLEANVALUE", isCommunity);
startActivity(intent);
}
});
}
Log.d("JSON Data", data.toString());
}
} catch (JSONException e) {
e.printStackTrace();
}
Log.d("JSON DATA", data.toString());
Log.w("Success Register", data.toString());
}
}).execute();
}
#Override
public void onError(String error) {
Log.e("Registration Error", error);
}
});
}
UPDATE
public class CommunityFragment extends ListFragment{
//LocationListener location;
ProgressDialog progressDialog;
Context context;
public static JSONObject parameters = new JSONObject();
private static final String STATE_LIST = "State Adapter Data";
public static final String DATA = "DATA";
public CustomerAccount customerAccount;
//---------Find Parameters----------
int byID;
//CustomListAdapter adapter;
public static String TAG = CommunityFragment.class.getSimpleName();
ListView listView;
ArrayList<RowItem> rowItem;
View view;
private static final String ARG_PARAM1 = "param1";
private static final String ARG_PARAM2 = "param2";
String searchname = ConstantSearch.SEARCHNAME;
CustomListAdapter adapter;
private String mParam1;
private String mParam2;
RowItemLoyalty getEndTask;
RowItem getTask;
RowItem storeData;
int index;
int top;
JSONArray array;
public CommunityFragment() {
}
public static CommunityFragment newInstance(String param1, String param2) {
CommunityFragment fragment = new CommunityFragment();
Bundle args = new Bundle();
args.putString(ARG_PARAM1, param1);
args.putString(ARG_PARAM2, param2);
fragment.setArguments(args);
return fragment;
}
#Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
String dataInJson = new Gson().toJson(rowItem);
outState.putString(DATA, dataInJson);
super.onSaveInstanceState(outState);
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
if(savedInstanceState != null && savedInstanceState.containsKey(DATA))
{
Log.d("StringData", DATA);
String jsonData = savedInstanceState.getString(DATA);
rowItem = new Gson().fromJson(jsonData, new TypeToken<List<RowItem>>(){}.getType());
}
else
{
rowItem = new ArrayList<>();
}
adapter = new CustomListAdapter(getActivity(), rowItem);
listView.setAdapter(adapter);
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
mParam1 = getArguments().getString(ARG_PARAM1);
mParam2 = getArguments().getString(ARG_PARAM2);
}
int radius = 4;
double latitude = 51.3674718208489;
double longtitude = -0.119329656538836;
Boolean isLoyalty = false;
int mer = 1;
try {
parameters.put(ConstantKeys.SEARCH_NAME, searchname);
parameters.put(ConstantKeys.LOYALTY, isLoyalty);
Log.d(CommunityFragment.class.getSimpleName(), parameters.toString());
} catch (JSONException e) {
e.printStackTrace();
}
FindOfferField();
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.community_fragment, container, false);
rowItem = new ArrayList<RowItem>();
listView = (ListView) rootView.findViewById(R.id.listViewCommunity);
return rootView;
}
public interface OnFragmentInteractionListener {
void onFragmentInteraction(Uri uri);
}
public void FindOfferField() {
RegisterRequest request = new RegisterRequest(getActivity());
SharedPreferences userpass = getActivity().getSharedPreferences("USERPASS", 0);
String email = userpass.getString("username", null);
String password = userpass.getString("password", null);
Log.d(CommunityFragment.class.getSimpleName(), "Email:" + email + " Password:" + password);
request.getToken(email, password, new ApiRequestListener() {
#Override
public void onSuccess(Object object) {
(new FindOfferTask() {
#Override
protected void onPostExecute(JSONObject data) {
super.onPostExecute(data);
try {
if (data.getString(ConstantKeys.RESULT).equals("OK")) {
array = data.getJSONArray(ConstantKeys.RESULTS);
RowItem items;
rowItem = new ArrayList<RowItem>();
for (int i = 0; i < array.length(); i++) {
final JSONObject offerList = array.getJSONObject(i);
items = new RowItem();
int id = Integer.parseInt(offerList.getString("Id"));
byID = id;
Log.d("AnotherID", String.valueOf(byID));
Boolean isCommunity = offerList.getBoolean(ConstantKeys.IS_COMMUNITY);
items.setId(offerList.getInt("Id"));
items.setMerchantid(offerList.getInt(ConstantKeys.FAVORITE_MERCHANTID));
items.setDescription(offerList.getString(ConstantKeys.DESCRIPTION));
items.setDateEnd(offerList.getString(ConstantKeys.DATE_END).replace("T00:00:00", ""));
items.setTokensFor(offerList.getString(ConstantKeys.TOKENSFOR));
if (!offerList.isNull("ImageId")) {
int bitmapImageID = offerList.getInt("ImageId");
Log.d("BITMAPHAHA", String.valueOf(bitmapImageID));
items.setImageId(bitmapImageID);
}
rowItem.add(items);
adapter = new CustomListAdapter(getActivity(), rowItem);
listView.setAdapter(adapter);
adapter.notifyDataSetChanged();
getEndTask = new RowItemLoyalty();
getTask = new RowItem();
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
boolean isCommunity = false;
try {
isCommunity = offerList.getBoolean(ConstantKeys.IS_COMMUNITY);
} catch (JSONException e) {
e.printStackTrace();
}
int offerID = rowItem.get(position).getId();
int merID = rowItem.get(position).getMerchantid();
Intent intent = new Intent(getActivity(), CustomerPromotion.class);
getEndTask.endTask();
getTask.endTask();
intent.putExtra("ID", offerID);
intent.putExtra("MERCHANT", merID);
intent.putExtra("BOOLEANVALUE", isCommunity);
startActivity(intent);
}
});
}
Log.d("JSON Data", data.toString());
}
} catch (JSONException e) {
e.printStackTrace();
}
Log.d("JSON DATA", data.toString());
Log.w("Success Register", data.toString());
}
}).execute();
}
#Override
public void onError(String error) {
Log.e("Registration Error", error);
}
});
}
public class FindOfferTask extends AsyncTask<Void, Void, JSONObject> {
#Override
protected void onPreExecute() {
super.onPreExecute();
progressDialog = new ProgressDialog(getActivity());
progressDialog.setMessage("Loading...");
progressDialog.setCancelable(false);
progressDialog.show();
}
#Override
protected JSONObject doInBackground(Void... params) {
ApiSecurityManager manager = ApiSecurityManager.getInstance();
String result = manager.apiCall("Offers/find", parameters.toString(), "C");
Log.d(CommunityFragment.class.getSimpleName(), result);
JSONObject jsonResult = new JSONObject();
Log.i(getClass().getSimpleName(), result);
try
{
jsonResult = new JSONObject(result);
}
catch (JSONException e)
{
e.printStackTrace();
}
return jsonResult;
}
protected void onPostExecute(JSONObject jsonObject) {
//loadingMore = false;
progressDialog.dismiss();
}
}
}
First of all, keep your view creation outside ApiRequestListener. Initialize all views in onCreateView() only.
// Key for storing data in `savedInstance`
public static final String DATA = "DATA";
In onCreateView()
public View onCreateView(LayoutInflater inflater,
ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.community_fragment, container, false);
rowItem = new ArrayList<RowItem>();
listView = (ListView) rootView.findViewById(R.id.listViewCommunity);
return rootView;
}
When activity is created, check if data is available in savedInstanceState or not and based on that start web service.
#Override
public void onActivityCreated(Bundle savedInstanceState)
{
super.onActivityCreated(savedInstanceState);
if(savedInstanceState.containsKey(DATA))
{
String jsonData = savedInstanceState.getString(DATA);
rowItem = new Gson().fromJson(jsonData, new TypeToken<List<RowItem>>(){}.getType());
}
else
{
rowItem = new ArrayList<>();
}
adapter = new CustomListAdapter(getActivity(), rowItem);
listView.setAdapter(adapter);
// Now here, check the size of array list. If it is 0, then start service to fetch data from server
}
To convert your list into string, I am using Gson library here.
#Override
public void onSaveInstanceState(Bundle outState)
{
// Here use gson library from google to convert list of data to string.
String dataInJson = new Gson().toJson(rowItem);
outState.putString(DATA, dataInJson);
super.onSaveInstanceState(outState);
}
And your method will look like this:
public void FindOfferField() {
RegisterRequest request = new RegisterRequest(getActivity());
SharedPreferences userpass = getActivity().getSharedPreferences("USERPASS", 0);
String email = userpass.getString("username", null);
String password = userpass.getString("password", null);
Log.d(CommunityFragment.class.getSimpleName(), "Email:" + email + " Password:" + password);
request.getToken(email, password, new ApiRequestListener() {
#Override
public void onSuccess(Object object) {
(new FindOfferTask() {
#Override
protected void onPostExecute(JSONObject data) {
super.onPostExecute(data);
try {
if (data.getString(ConstantKeys.RESULT).equals("OK")) {
array = data.getJSONArray(ConstantKeys.RESULTS);
RowItem items;
for (int i = 0; i < array.length(); i++) {
final JSONObject list = array.getJSONObject(i);
items = new RowItem();
int id = Integer.parseInt(offerList.getString("Id"));
byID = id;
Log.d("AnotherID", String.valueOf(byID));
Boolean isCommunity = offerList.getBoolean(ConstantKeys.IS_COMMUNITY);
items.setId(list.getInt("Id"));
items.setMerchantid(list.getInt(ConstantKeys.MERCHANTID));
items.setDescription(list.getString(ConstantKeys.DESCRIPTION));
items.setDateEnd(list.getString(ConstantKeys.DATE).replace("T00:00:00", ""));
items.setTokensFor(list.getString(ConstantKeys.FOR));
if (!offerList.isNull("ImageId")) {
int bitmapImageID = offerList.getInt("ImageId");
Log.d("BITMAPHAHA", String.valueOf(bitmapImageID));
items.setImageId(bitmapImageID);
}
rowItem.add(items);
adapter.notifyDataSetChanged();
getEndTask = new RowItemLoyalty();
getTask = new RowItem();
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
boolean isCommunity = false;
try {
isCommunity = offerList.getBoolean(ConstantKeys.IS_COMMUNITY);
} catch (JSONException e) {
e.printStackTrace();
}
int ID = rowItem.get(position).getId();
int merID = rowItem.get(position).getMerchantid();
Intent intent = new Intent(getActivity(), CustomerPromotion.class);
getEndTask.endTask();
getTask.endTask();
intent.putExtra("ID", ID);
intent.putExtra("MERCHANT", merID);
intent.putExtra("BOOLEANVALUE", isCommunity);
startActivity(intent);
}
});
}
Log.d("JSON Data", data.toString());
}
} catch (JSONException e) {
e.printStackTrace();
}
Log.d("JSON DATA", data.toString());
Log.w("Success Register", data.toString());
}
}).execute();
}
#Override
public void onError(String error) {
Log.e("Registration Error", error);
}
});
}
Hope this helps.
While scrolling down the listview I am getting IndexOutOfBound exception.
Let me explain the Scenario:-
At first the list is populated by the data that I am getting from the server. -- No Error
Second when I am PULL TO REFRESHing to get the data and at the same time when I am scrolling I am getting IndexOutofBound Exception.
I got stuck in this scenario.
Please help.
Here is my code:-
NewOrders.java
public class NewOrders extends Fragment implements
SwipeRefreshLayout.OnRefreshListener {
private ListView listView;
private SwipeRefreshLayout swipeRefreshLayout;
NewOrderListviewAdapter adp;
public static String allResId = "", boy_id = "";
String passedArg = "";
DialogView dialogView;
private Boolean isRefreshing = false;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_neworders,
container, false);
dialogView = new DialogView();
listView = (ListView) rootView.findViewById(R.id.list);
swipeRefreshLayout = (SwipeRefreshLayout) rootView
.findViewById(R.id.swipe_refresh_layout);
new getNewOrders().execute();
swipeRefreshLayout.setOnRefreshListener(this);
return rootView;
}
public class getNewOrders extends AsyncTask<Void, String, String> {
String strMessage;
#Override
protected void onPreExecute() {
// if (!PendingOrderListDataStorage.NEW_ORDER.isEmpty())
// PendingOrderListDataStorage.NEW_ORDER.clear();
// showing refresh animation before making http call
swipeRefreshLayout.setRefreshing(true);
}
#Override
protected String doInBackground(Void... params) {
HttpClient httpClient = SessionControl.getHttpclient();
String url = ServiceAPIs.PENDING_ORDER_LIST;
HttpPost httppost = new HttpPost(url);
try {
List<NameValuePair> valuepair = new ArrayList<NameValuePair>();
String resIds = "";
for (int i = 0; i < PendingOrderListDataStorage.RESTAURANT_LIST
.size(); i++) {
resIds = resIds
+ ","
+ PendingOrderListDataStorage.RESTAURANT_LIST
.get(i).restaurant_id;
}
resIds = resIds.substring(1);
valuepair.add(new BasicNameValuePair("res_id", resIds));
Log.d("RID", allResId);
valuepair.add(new BasicNameValuePair("boy_id", passedArg));
Log.d("BID", passedArg);
httppost.setEntity(new UrlEncodedFormEntity(valuepair));
HttpResponse httpResponse = httpClient.execute(httppost);
StatusLine statusLine = httpResponse.getStatusLine();
int statusCode = statusLine.getStatusCode();
if (statusCode == 200) {
HttpEntity httpEntity = httpResponse.getEntity();
if (httpEntity != null) {
InputStream instream = httpEntity.getContent();
strMessage = Converter.inputStreamToString(instream)
.toString();
}
} else {
return null;
}
} catch (ClientProtocolException e) {
e.printStackTrace();
return null;
} catch (IOException e) {
e.printStackTrace();
return null;
} finally {
httpClient.getConnectionManager().closeExpiredConnections();
}
return strMessage;
}
#Override
protected void onProgressUpdate(String... progress) {
super.onProgressUpdate(progress);
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
// stopping swipe refresh
swipeRefreshLayout.setRefreshing(false);
isRefreshing = false;
Log.d("BID from Rending for Delivery", passedArg);
if (result != null) {
Log.v("Result", result);
try {
JSONObject jsonObj = new JSONObject(result);
String status = jsonObj.getString("status");
if (status.equals("0")) {
System.out.print("No Pending Orders");
} else {
JSONArray array = jsonObj.getJSONArray("data");
if (array.length() > 0) {
for (int i = 0; i < array.length(); i++) {
JSONObject obj = array.getJSONObject(i);
if (obj.getString("delivery_boy_status")
.equals("P")) {
String deliveryDate = "";
if (obj.getString("deliverydate").contains(
"/")) {
deliveryDate = convertDate(obj
.getString("deliverydate"));
}
else {
deliveryDate = obj
.getString("deliverydate");
}
NewOrderListObjectItem ObjectItemData = new NewOrderListObjectItem(
obj.getString("restaurant_name"),
obj.getString("status"),
obj.getString("delivery_boy_status"),
obj.getString("app_order_status"),
obj.getString("orderid"),
obj.getString("ordergenerateid"),
obj.getString("customer_id"),
obj.getString("usertype"),
obj.getString("customername"),
obj.getString("customerlastname"),
obj.getString("customeremail"),
obj.getString("customercellphone"),
obj.getString("customerlandline"),
obj.getString("deliverydoornumber"),
obj.getString("deliverystreet"),
obj.getString("deliverylandmark"),
obj.getString("deliveryarea"), obj
.getString("cityname"), obj
.getString("zipcode"),
obj.getString("deliverystate"), obj
.getString("deliverytype"),
obj.getString("foodassoonas"),
deliveryDate, obj
.getString("deliverytime"),
obj.getString("ordertotalprice"),
obj.getString("payment_type"),
obj.getString("paypal_status"), obj
.getString("orderdate"));
// PendingOrderListDataStorage.NEW_ORDER
// .clear();
if (!PendingOrderListDataStorage.NEW_ORDER
.isEmpty())
PendingOrderListDataStorage.NEW_ORDER
.clear();
PendingOrderListDataStorage.NEW_ORDER
.add(ObjectItemData);
}
}
}
}
if (adp != null)
adp.notifyDataSetChanged();
else
makeList();
} catch (JSONException e) {
e.printStackTrace();
dialogView.showCustomToast(getActivity(), "Error");
}
} else {
dialogView.showCustomToast(getActivity(),
"Please Check your Internet Connection");
}
}
private void makeList() {
Log.d("Size: From New Orders List", ""
+ PendingOrderListDataStorage.NEW_ORDER.size());
if (PendingOrderListDataStorage.NEW_ORDER.size() > 0) {
adp = new NewOrderListviewAdapter(getActivity(),
R.layout.order_item_new,
PendingOrderListDataStorage.NEW_ORDER);
listView.setAdapter(adp);
adp.notifyDataSetChanged();
}
}
#SuppressLint("SimpleDateFormat")
String convertDate(String inputDate) {
SimpleDateFormat theDateFormat = new SimpleDateFormat("MM/dd/yyyy");
Date date = null;
try {
date = theDateFormat.parse(inputDate);
} catch (ParseException parseException) {
// Date is invalid. Do what you want.
} catch (Exception exception) {
// Generic catch. Do what you want.
}
theDateFormat = new SimpleDateFormat("yyyy-MM-dd");
return theDateFormat.format(date);
}
}
#Override
public void onRefresh() {
swipeRefreshLayout.setRefreshing(true);
if (!isRefreshing) {
isRefreshing = true;
new getNewOrders().execute();
}
}
}
NewOrderListViewAdapter.java
#Override
public View getView(final int position, View convertView,
final ViewGroup parent) {
final ViewHolder holder;
LayoutInflater inflater = ((Activity) mContext).getLayoutInflater();
if (convertView == null) {
convertView = inflater.inflate(layoutResourceId, null);
holder = new ViewHolder();
holder.btn_confirm = (TextView) convertView
.findViewById(R.id.confirm);
holder.btn_details = (TextView) convertView
.findViewById(R.id.details);
holder.title = (TextView) convertView.findViewById(R.id.title);
holder.orderDateTime = (TextView) convertView
.findViewById(R.id.orderDateTime);
holder.deliveryDateTime = (TextView) convertView
.findViewById(R.id.deliveryDateTime);
holder.orderNumberCode = (TextView) convertView
.findViewById(R.id.orderNumberCode);
holder.orderAddressName = (TextView) convertView
.findViewById(R.id.orderAddressName);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
NewOrderListObjectItem list = data.get(position);
holder.title.setText(list.getRestaurant_name());
Log.d("RestaurantName", list.getRestaurant_name());
holder.orderNumberCode.setText("#ORD " + list.getOrderid());
Log.d("Order No.:", "#ORD" + list.getOrderid());
holder.orderDateTime.setText(list.customername + " "
+ list.customerlastname);
Log.d("Order Date & Time", list.getOrderdate());
holder.deliveryDateTime.setText(list.getDeliverydate() + " "
+ list.getDeliverytime());
Log.d("Delivery Date & Time",
list.getDeliverydate() + "" + list.getDeliverytime());
holder.orderAddressName.setText(list.getDeliverystreet() + ", "
+ list.getDeliveryarea() + ", " + list.getDeliverycity() + ", "
+ list.getDeliverystate() + ", " + list.getDeliverystate());
holder.btn_details.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Intent next = new Intent(mContext, Orders.class);
Bundle bundle = new Bundle();
bundle.putString("order_id", holder.orderNumberCode.getText()
.toString());
Log.d("Order Id: ", holder.orderNumberCode.getText().toString());
bundle.putString("order_status", order_status);
Log.d("Order Status: ", order_status);
bundle.putInt("gridPositionClicked", position);
next.putExtras(bundle);
mContext.startActivity(next);
((Activity) mContext).overridePendingTransition(
R.anim.push_left_in, R.anim.push_left_out);
((Activity) mContext).finish();
}
});
holder.btn_confirm.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
boy_id = GlobalVariable.boy_id_one;
order_id = holder.orderNumberCode.getText().toString();
Log.d("CONFIRM_BUTTON", order_id);
new changeOrderStatus().execute();
}
});
return convertView;
}
You are clearing PendingOrderListDataStorage.NEW_ORDER.clear();
in preExecute of your Asynctast, instead clear the array before you add new data to the list in the Onpostexecute of your Asynctask.