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.
Related
I have a recycle view which gets data from an sql table,its basically like a chat system app.
but of course i need to refresh data every time it changes,however i tried using .notifyDataSetChanged().
but it couldn't appear to be working for me,can anyone help me with this task According to my code
here is my code:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_chat);
getSupportActionBar().hide();
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
emojiButton = findViewById(R.id.emoji_button);
submitButton = findViewById(R.id.submit_button);
emojiconEditText = findViewById(R.id.emojicon_edit_text);
emojIconActions = new EmojIconActions(getApplicationContext(),activity_chat,emojiButton,emojiconEditText);
SyncData syncData = new SyncData();
syncData.SyncoData("");
syncData.execute();
//emojIconActions.ShowEmojicon();
submitButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
try{
String editTextData = emojiconEditText.getText().toString();
SyncData orderdata = new SyncData();
orderdata.SyncData(editTextData);
Date c = Calendar.getInstance().getTime();
SimpleDateFormat df = new SimpleDateFormat("MM/dd/yyyy");
String formattedDate = df.format(c);
orderdata.SyncoData("Insert into CustomerSupportChat values('" + formattedDate + "','" + editTextData + "','Customer','3','" + getIntent().getStringExtra("nameid") + "','1','1') ");
orderdata.execute();
emojiconEditText.setText("");
emojiconEditText.requestFocus();
}
catch(Exception e) {
Log.e("ActivityName", "Exception caused by editText " + e.toString());
}
}
});
connectionClass = new ConnectionClass();
itemArrayList = new ArrayList<ClassListChat>();
listOfMessage = findViewById(R.id.list_of_message);
MyAppAdapter appAdapter = new MyAppAdapter(itemArrayList,ChatActivity.this);
listOfMessage.setAdapter(appAdapter);
LinearLayoutManager linearLayoutManager = new LinearLayoutManager(ChatActivity.this);
linearLayoutManager.setReverseLayout(true);
listOfMessage.setLayoutManager(linearLayoutManager);
}
private class SyncData extends AsyncTask<String, String, String> {
String msg;
ProgressDialog progress;
String editTextData;
Date c = Calendar.getInstance().getTime();
SimpleDateFormat df = new SimpleDateFormat("MM/dd/yyyy");
String formattedDate = df.format(c);
public void SyncData(String editTextData) {
this.editTextData = editTextData;
}
String inquery = "Insert into CustomerSupportChat values('" + formattedDate + "','" + editTextData + "','Customer','3','" + getIntent().getStringExtra("nameid") + "','1','1') ";
public void SyncoData(String inquery) {
this.inquery = inquery;
}
#Override
protected void onPreExecute() //Starts the progress dailog
{
progress = ProgressDialog.show(ChatActivity.this, "Loading...",
"Please Wait...", true);
}
#Override
protected String doInBackground(String... strings) // Connect to the database, write query and add items to array list
{
runOnUiThread(new Runnable() {
public void run() {
try {
Connection conn = connectionClass.CONN(); //Connection Object
if (conn == null) {
success = false;
msg = "Sorry something went wrong,Please check your internet connection";
} else {
// Change below query according to your own database.
Date c = Calendar.getInstance().getTime();
SimpleDateFormat df = new SimpleDateFormat("MM/dd/yyyy");
String formattedDate = df.format(c);
System.out.println("it isssssssssssssssssssssssssssssssssssssssssaaaaaaaaaaaaaaaaaaaa" + formattedDate);
String query = inquery +
"Select MessageID,MessageDate,MessageText,SenderType,MessageRecieved,MessageReaded,CustomerData.CustomerName,StoresData.StoreEnglishName,StoresData.StoreArabicName FROM " +
"CustomerSupportChat INNER JOIN CustomerData ON " +
"CustomerSupportChat.CustomerID = CustomerData.CustomerID INNER JOIN StoresData ON " +
"CustomerSupportChat.StoreID = StoresData.StoreID ORDER BY MessageID DESC";
// String query2 =
// "Select MessageID,MessageDate,MessageText,SenderType,MessageRecieved,MessageReaded,Users_Login_Data.Username,StoresData.StoreEnglishName,StoresData.StoreArabicName FROM " +
// "CustomerSupportChat INNER JOIN Users_Login_Data ON " +
// "CustomerSupportChat.CustomerID = Users_Login_Data.CustomerID INNER JOIN StoresData ON " +
// "CustomerSupportChat.StoreID = StoresData.StoreID Where SenderType = 'Store' ORDER BY MessageID DESC";
//Statement stmt2 = conn.createStatement();
// ResultSet rs2 = stmt2.executeQuery(query2);
Statement stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery(query);
itemArrayList.clear();
if (rs != null) // if resultset not null, I add items to itemArraylist using class created
{
while (rs.next()) {
try {
itemArrayList.add(new ClassListChat(rs.getString("MessageText"), rs.getString("SenderType"), rs.getString("MessageText")));
} catch (Exception ex) {
ex.printStackTrace();
}
}
msg = "Found";
success = true;
} else {
msg = "No Data found!";
success = false;
}
// if ( rs2 != null){
// while (rs2.next()){
// itemArrayList.add(new ClassListChat("","Store",rs2.getString("MessageText")));
// }
// }
}
} catch (Exception e) {
e.printStackTrace();
Writer writer = new StringWriter();
e.printStackTrace(new PrintWriter(writer));
msg = writer.toString();
Log.d("Error", writer.toString());
success = false;
}
}
});
return msg;
}
#Override
protected void onPostExecute(String msg) // disimissing progress dialoge, showing error and setting up my listview
{
progress.dismiss();
if (msg != null) {
Toast.makeText(ChatActivity.this, msg + "", Toast.LENGTH_LONG).show();
}
if (!success) {
Toast.makeText(ChatActivity.this,"ERROR " + msg,Toast.LENGTH_LONG).show();
} else {
try {
MyAppAdapter appAdapter = new MyAppAdapter(itemArrayList,ChatActivity.this);
listOfMessage.setAdapter(appAdapter);
LinearLayoutManager linearLayoutManager = new LinearLayoutManager(ChatActivity.this);
linearLayoutManager.setReverseLayout(true);
listOfMessage.setLayoutManager(linearLayoutManager);
} catch (Exception ex) {
}
}
}
}
public class MyAppAdapter extends RecyclerView.Adapter<MyAppAdapter.ViewHolder>//has a class viewholder which holds
{
private ArrayList<ClassListChat> mOriginalValues; // Original Values
private ArrayList<ClassListChat> mDisplayedValues;
public class ViewHolder extends RecyclerView.ViewHolder {
TextView messageText;
TextView messageStore;
TextView messageUser;
TextView messageTime;
public ViewHolder(#NonNull View itemView) {
super(itemView);
messageText = itemView.findViewById(R.id.message_text);
messageUser = itemView.findViewById(R.id.message_user);
messageTime = itemView.findViewById(R.id.message_time);
messageStore = itemView.findViewById(R.id.message_text_store);
}
}
public List <ClassListChat> parkingList;
public Context context;
ArrayList<ClassListChat> arraylist;
private MyAppAdapter(List<ClassListChat> apps, Context context) {
this.parkingList = apps;
this.context = context;
arraylist = new ArrayList<ClassListChat>();
arraylist.addAll(parkingList);
}
#Override
public MyAppAdapter.ViewHolder onCreateViewHolder(ViewGroup parent,int viewType) {
View rowView = LayoutInflater.from(parent.getContext()).inflate(R.layout.listcontentstorechat,parent,false);
ViewHolder viewHolder = new ViewHolder(rowView);
LayoutInflater inflater = getLayoutInflater();
rowView = inflater.inflate(R.layout.listcontentstorechat, parent, false);
// here setting up names and images
return viewHolder;
}
#Override
public void onBindViewHolder(#NonNull ViewHolder holder, int position) {
holder.messageUser.setText(parkingList.get(position).getMessageUser());
holder.messageTime.setText(DateFormat.format("dd-MM-yyyy (HH:mm:ss)", parkingList.get(position).getMessageTime()));
if (holder.messageUser.getText().toString().equals("Store")){
RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT);
params.topMargin = 45;
params.addRule(RelativeLayout.ALIGN_PARENT_LEFT);
holder.messageUser.setLayoutParams(params);
holder.messageStore.setText(parkingList.get(position).getMessageOther());
}else {
RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT);
params.topMargin = 2;
params.addRule(RelativeLayout.ALIGN_PARENT_RIGHT);
holder.messageUser.setLayoutParams(params);
holder.messageText.setText(parkingList.get(position).getMessageText());
}
if (holder.messageText.getText().toString().equals("")){
holder.messageText.setVisibility(View.GONE);
}
if (holder.messageStore.getText().toString().equals("")){
holder.messageStore.setVisibility(View.GONE);
}
holder.setIsRecyclable(false);
myAppAdapter.notifyDataSetChanged();
System.out.println("COUNTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTT:"+myAppAdapter.getItemCount());
}
#Override
public int getItemCount() {
return arraylist.size();
}
}
if you noticed i already added .notifyDataSetChanged() in the last line of onBindViewHolder(),but it returns an error in the logcat saying that getItemCount() is null,i also tried putting
if(arraylist != null){
return arraylist.size();
}
but it doesn't also work.
also the print statement which says "COUNTTT" doesn't print anything.
any help?!
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...
Main Activity:
public class MainActivity extends AppCompatActivity {
// ImageView iv;
public static StringBuffer finalparsedData;
public static GridView myGrid;
private static final String TAG = MainActivity.class.getSimpleName();
ArrayList<String> values = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
myGrid=(GridView)findViewById(R.id.grid_view);
Button btnHit = (Button) findViewById(R.id.btnHit);
btnHit.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v) {
new JSONTask().execute("https://api.flickr.com/services/rest/?method=flickr.photos.getRecent&" +
"api_key=46e71c8d2b35ba8c9c333a462ec8aea7&per_page=3&format=json&nojsoncallback=10");
}
});
values = new ArrayList<>();
}
/*static boolean isAirplaneModeOn(Context context) {
ContentResolver contentResolver = context.getContentResolver();
return Settings.System.getInt(contentResolver, AIRPLANE_MODE_ON, 0) != 0;
}*/
public class JSONTask extends AsyncTask<String, Void, String> {
String photoid;
int farm;
String server;
String secret;
#Override
protected String doInBackground(String... params) {
HttpURLConnection connection = null;
BufferedReader reader = null;
StringBuffer buffer = null;
JSONArray parentarray = null;
try {
URL url = new URL(params[0]);
connection = (HttpURLConnection) url.openConnection();
connection.connect();
InputStream stream = connection.getInputStream();
reader = new BufferedReader(new InputStreamReader(stream));
buffer = new StringBuffer();
String line = "";
while ((line = reader.readLine()) != null) {
buffer.append(line);
}
String finalJson = buffer.toString();
JSONObject parentObject = new JSONObject(finalJson);
//JSONObject initialObject = new JSONObject("photos");
JSONObject initialObject = parentObject.getJSONObject("photos");
parentarray = initialObject.getJSONArray("photo");
finalparsedData = new StringBuffer();
for (int i = 0; i < parentarray.length(); i++) {
JSONObject finalObject = parentarray.getJSONObject(i);
photoid = finalObject.optString("id");
farm = finalObject.optInt("farm");
server = finalObject.optString("server");
secret = finalObject.optString("secret");
finalparsedData.append("https://farm" + farm + ".staticflickr.com/" + server + "/" + photoid+ "_" + secret + ".jpg" +"\n\n");
values.add(String.valueOf((finalparsedData)));
}
return "done";
} catch (MalformedURLException e) {
e.printStackTrace();
return "error";
} catch (IOException e) {
e.printStackTrace();
return "error";
} catch (JSONException e) {
e.printStackTrace();
return "error";
} finally {
if (connection != null) {
connection.disconnect();
}
try {
if (reader != null) {
reader.close();
return "done";
}
} catch (IOException e) {
e.printStackTrace();
return "error";
}
}
}
#Override
protected void onPostExecute(String result) {
switch (result){
case "done":
MyImageAdapter adapter = new MyImageAdapter(MainActivity.this, values);
myGrid.setAdapter((ListAdapter) adapter);
break;
}
}
}
}
MyAdapterClass:
public class MyImageAdapter extends BaseAdapter {
ArrayList<String> values;
Context mContext;
public MyImageAdapter(Context mContext, ArrayList<String> values) {
this.values = values;
this.mContext = mContext;
}
#Override
public int getCount() {
return values.size();
}
#Override
public Object getItem(int position) {
return position;
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View row = convertView;
ViewHolder holder;
;
if (row == null){
LayoutInflater inflater = (LayoutInflater)mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
row = inflater.inflate(R.layout.grid,parent,false);
holder = new ViewHolder();
holder.imageView = (ImageView) row.findViewById(R.id.image_View);
row.setTag(holder);
} else {
holder = (ViewHolder) row.getTag();
}
String image = values.get(position);
Picasso.with(mContext).load(image).into(holder.imageView);
return row;
}
public class ViewHolder {
ImageView imageView;
}
}
I got a problem during images loading in gridview, out of 10 images only 1 image is shown and rest of them showing "this images is no longer available"
Hahaha, silly mistake. Just replace your for loop inside JSONTask with this,
.
.
.
for (int i = 0; i < parentarray.length(); i++) {
JSONObject finalObject = parentarray.getJSONObject(i);
photoid = finalObject.optString("id");
farm = finalObject.optInt("farm");
server = finalObject.optString("server");
secret = finalObject.optString("secret");
String fullPath = "https://farm" + farm + ".staticflickr.com/" + server + "/" + photoid+ "_" + secret + ".jpg";
values.add(fullPath);
}
.
.
.
No need to use StringBuffer. You should use normal String variable. :)
i am not able to populate the imageview textview inside gridview using fragments.
It is showing blank intead of gridview populating in my project can please anyone see the code below and let me know what i have to change
And the populating the image and text is from the mysql database dynamically
public class StoreHomeFragment extends Fragment {
final ArrayList<HashMap<String, String>> MyArrList = new ArrayList<HashMap<String, String>>();
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.store_home, container, false);
final GridView gridView1 = (GridView)rootView.findViewById(R.id.store_home_gridview);
gridView1.setAdapter(new ImageAdapter(rootView.getContext(), MyArrList));
return rootView;
}
//Activity is created
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
String url = "http://192.168.1.132/Android/App/good.php"; //url where i am using select query and retrieving it from database
try {
JSONArray data = new JSONArray(getJSONUrl(url));
HashMap<String, String> map;
for(int i = 0; i < data.length(); i++){
JSONObject c = data.getJSONObject(i);//retrieving from db
map = new HashMap<String, String>();
map.put("name", c.getString("name"));
map.put("artist", c.getString("artist"));
map.put("price", c.getString("price"));
map.put("image", c.getString("image"));
MyArrList.add(map);
}
//gridView1.setAdapter(new ImageAdapter(this,MyArrList));
} catch (JSONException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
//I have used imageAdapter
class ImageAdapter extends BaseAdapter
{
private Context context;
public ImageView imageView;
private ArrayList<HashMap<String, String>> MyArr = new ArrayList<HashMap<String, String>>();
public ImageAdapter(Context c,ArrayList<HashMap<String, String>> list)
{
context = c;
MyArr = list;
}
public int getCount() {
return MyArr.size();
}
public Object getItem(int position) {
return position;
}
public long getItemId(int position) {
return position;
}
public View getView(int position, View convertView, ViewGroup parent) {
LayoutInflater inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
if (convertView == null) {
convertView = inflater.inflate(R.layout.store_home_gridview_row, null);
}
TextView tv_title = (TextView) convertView.findViewById(R.id.textview_name);
tv_title.setText("Title:"+MyArr.get(position).get("name"));
TextView tv_artist = (TextView) convertView.findViewById(R.id.textview_artist);
tv_artist.setText("Artist:"+MyArr.get(position).get("artist"));
TextView tv_duration = (TextView) convertView.findViewById(R.id.textview_price);
tv_duration.setText("Price:"+MyArr.get(position).get("price"));
String abc = (MyArr.get(position).get("image"));
String abcd = "http://192.168.1.132/images/products/"+abc;
imageView = (ImageView) convertView.findViewById(R.id.imageView1);
try
{
URL url3 = null;
try {
url3 = new URL(abcd);
} catch (Exception e) {
e.printStackTrace();
}
Bitmap bmp = BitmapFactory.decodeStream(url3.openConnection().getInputStream()); //image is populated
imageView.setImageBitmap(bmp);
}
catch(Exception par)
{
imageView.setImageResource(android.R.drawable.ic_menu_report_image);
}
return convertView;
}
}
/*** Get JSON Code from URL ***/
public String getJSONUrl(String url) {
StringBuilder str = new StringBuilder();
HttpClient client = new DefaultHttpClient();
HttpGet httpGet = new HttpGet(url);
try
{
HttpResponse response = client.execute(httpGet);
StatusLine statusLine = response.getStatusLine();
int statusCode = statusLine.getStatusCode();
System.out.println ( "status Code : " + statusCode );
if (statusCode == 200)
{
HttpEntity entity = response.getEntity();
InputStream content = entity.getContent();
BufferedReader reader = new BufferedReader(new InputStreamReader(content));
String line;
while ((line = reader.readLine()) != null)
{
str.append(line);
}
}
else
{
Log.e("Log", "Failed to download file..");
}
}
catch (ClientProtocolException e)
{
e.printStackTrace();
}
catch (IOException e)
{
e.printStackTrace();
}
System.out.println ( "str : " + str.toString() );
return str.toString();
}
}
Follow the steps Hope this helps you
1) Remove these lines from onCreateView() method
final GridView gridView1 = (GridView)rootView.findViewById(R.id.store_home_gridview);
gridView1.setAdapter(new ImageAdapter(rootView.getContext(), MyArrList));
2)Modify onActivityCreated() as follow
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
new AsyncTask<Void, Void, Void>() {
#Override
protected Void doInBackground(Void... params) {
String url = "http://192.168.1.132/Android/App/good.php";
try {
JSONArray data = new JSONArray(getJSONUrl(url));
HashMap<String, String> map;
for (int i = 0; i < data.length(); i++) {
JSONObject c = data.getJSONObject(i);
map = new HashMap<String, String>();
map.put("name", c.getString("name"));
map.put("artist", c.getString("artist"));
map.put("price", c.getString("price"));
map.put("image", c.getString("image"));
MyArrList.add(map);
}
} catch (JSONException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
final GridView gridView1 = (GridView) rootView.findViewById(R.id.store_home_gridview);
gridView1.setAdapter(new ImageAdapter(getActivity(), MyArrList));
}
}.execute();
}
I have an async task which populates a spinner with data. The spinner data comes from objects in a list. My problem is when I set the onclick listener for the items in the list I also want the id from the object not just the name:
public class PortfolioGetAllLists extends AsyncTask<String, Void, String> {
Context c;
PortfolioGetAllBeers.OnArticleSelectedListener useThis;
private ProgressDialog Dialog;
public PortfolioGetAllLists (Context context, PortfolioGetAllBeers.OnArticleSelectedListener thisListener)
{
c = context;
useThis = thisListener;
Dialog = new ProgressDialog(c);
}
#Override
protected String doInBackground(String... arg0) {
// TODO Auto-generated method stub
return readJSONFeed(arg0[0]);
}
protected void onPreExecute() {
Dialog.setMessage("Getting Brewery List");
Dialog.setTitle("Loading");
Dialog.setCancelable(false);
Dialog.show();
}
protected void onPostExecute(String result){
//decode json here
try{
JSONArray jsonArray = new JSONArray(result);
//acces listview
final ListView lv = (ListView) ((Activity) c).findViewById(R.id.allYourBeersList);
//make array list for beer
final List<String> tasteList = new ArrayList<String>();
tasteList.add("");
for(int i = 0; i < jsonArray.length(); i++) {
String bID = jsonArray.getJSONObject(i).getString("id");
String beer = jsonArray.getJSONObject(i).getString("name");
String rate = "na";
String beerID = "na";
//create object
ShortBeerInfo tempTaste = new ShortBeerInfo(beer, rate, beerID, bID);
//add to arraylist
tasteList.add(beer);
}
// Selection of the spinner
Spinner spinner = (Spinner) ((Activity) c).findViewById(R.id.portfolioSpinner2);
// Application of the Array to the Spinner
ArrayAdapter<String> spinnerArrayAdapter = new ArrayAdapter<String>(c, android.R.layout.simple_spinner_item,tasteList );
spinnerArrayAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); // The drop down view
spinner.setAdapter(spinnerArrayAdapter);
//add on item selected
final Spinner portfolioType = (Spinner) ((Activity) c).findViewById(R.id.portfolioSpinner2);
portfolioType.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parentView, View selectedItemView, int position, long id) {
String portfolioChoice = portfolioType.getSelectedItem().toString();
//Toast.makeText(((Activity) c).getApplicationContext(), portfolioChoice, Toast.LENGTH_LONG).show();
lv.setAdapter(null);
//get brewery beers
//get userID
//get user data
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(selectedItemView.getContext());
String userID = prefs.getString("userID", null);
try {
portfolioChoice = URLEncoder.encode(portfolioChoice, "UTF-8");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
//construct url
String url = "myURL";
Log.d("portfolio", url);
//async task goes here
//new PortfolioGetAllBeers(selectedItemView.getContext()).execute(url);
PortfolioGetAllBeers task = new PortfolioGetAllBeers(c);
task.setOnArticleSelectedListener(useThis);
task.execute(url);
}
#Override
public void onNothingSelected(AdapterView<?> parentView) {
// do nothing
}
});
}
catch(Exception e){
}
Dialog.dismiss();
}
public String readJSONFeed(String URL) {
StringBuilder stringBuilder = new StringBuilder();
HttpClient httpClient = new DefaultHttpClient();
HttpGet httpGet = new HttpGet(URL);
try {
HttpResponse response = httpClient.execute(httpGet);
StatusLine statusLine = response.getStatusLine();
int statusCode = statusLine.getStatusCode();
if (statusCode == 200) {
HttpEntity entity = response.getEntity();
InputStream inputStream = entity.getContent();
BufferedReader reader = new BufferedReader(
new InputStreamReader(inputStream));
String line;
while ((line = reader.readLine()) != null) {
stringBuilder.append(line);
}
inputStream.close();
} else {
Log.d("JSON", "Failed to download file");
}
} catch (Exception e) {
Log.d("readJSONFeed", e.getLocalizedMessage());
}
return stringBuilder.toString();
}
}
This line below is the line which get the beers name, but I do not know how to get also the id from the object which sets the listview name:
String portfolioChoice = portfolioType.getSelectedItem().toString();
Update:
I have changed my above code to this to incorporate a custom adapter:
public class PortfolioGetAllLists extends AsyncTask<String, Void, String> {
Context c;
PortfolioGetAllBeers.OnArticleSelectedListener useThis;
private ProgressDialog Dialog;
public PortfolioGetAllLists (Context context, PortfolioGetAllBeers.OnArticleSelectedListener thisListener)
{
c = context;
useThis = thisListener;
Dialog = new ProgressDialog(c);
}
#Override
protected String doInBackground(String... arg0) {
// TODO Auto-generated method stub
return readJSONFeed(arg0[0]);
}
protected void onPreExecute() {
Dialog.setMessage("Getting Brewery List");
Dialog.setTitle("Loading");
Dialog.setCancelable(false);
Dialog.show();
}
protected void onPostExecute(String result){
//decode json here
try{
JSONArray jsonArray = new JSONArray(result);
//acces listview
final ListView lv = (ListView) ((Activity) c).findViewById(R.id.allYourBeersList);
//make array list for beer
final List<ShortBeerInfo> tasteList = new ArrayList<ShortBeerInfo>();
//tasteList.add("");
for(int i = 0; i < jsonArray.length(); i++) {
String bID = jsonArray.getJSONObject(i).getString("id");
String beer = jsonArray.getJSONObject(i).getString("name");
String rate = "na";
String beerID = "na";
//create object
ShortBeerInfo tempTaste = new ShortBeerInfo(beer, rate, beerID, bID);
//add to arraylist
tasteList.add(tempTaste);
}
// Selection of the spinner
Spinner spinner = (Spinner) ((Activity) c).findViewById(R.id.portfolioSpinner2);
// Application of the Array to the Spinner
ShortBeerInfoAdapter<ShortBeerInfo> spinnerArrayAdapter = new ArrayAdapter<ShortBeerInfo>(c, android.R.layout.simple_spinner_item,tasteList );
spinnerArrayAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); // The drop down view
spinner.setAdapter(spinnerArrayAdapter);
//add on item selected
final Spinner portfolioType = (Spinner) ((Activity) c).findViewById(R.id.portfolioSpinner2);
portfolioType.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parentView, View selectedItemView, int position, long id) {
String portfolioChoice = portfolioType.getSelectedItem().toString();
//Toast.makeText(((Activity) c).getApplicationContext(), portfolioChoice, Toast.LENGTH_LONG).show();
lv.setAdapter(null);
//get brewery beers
//get userID
//get user data
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(selectedItemView.getContext());
String userID = prefs.getString("userID", null);
try {
portfolioChoice = URLEncoder.encode(portfolioChoice, "UTF-8");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
//construct url
String url = "myURL";
Log.d("portfolio", url);
//async task goes here
//new PortfolioGetAllBeers(selectedItemView.getContext()).execute(url);
PortfolioGetAllBeers task = new PortfolioGetAllBeers(c);
task.setOnArticleSelectedListener(useThis);
task.execute(url);
}
#Override
public void onNothingSelected(AdapterView<?> parentView) {
// do nothing
}
});
}
catch(Exception e){
}
Dialog.dismiss();
}
public String readJSONFeed(String URL) {
StringBuilder stringBuilder = new StringBuilder();
HttpClient httpClient = new DefaultHttpClient();
HttpGet httpGet = new HttpGet(URL);
try {
HttpResponse response = httpClient.execute(httpGet);
StatusLine statusLine = response.getStatusLine();
int statusCode = statusLine.getStatusCode();
if (statusCode == 200) {
HttpEntity entity = response.getEntity();
InputStream inputStream = entity.getContent();
BufferedReader reader = new BufferedReader(
new InputStreamReader(inputStream));
String line;
while ((line = reader.readLine()) != null) {
stringBuilder.append(line);
}
inputStream.close();
} else {
Log.d("JSON", "Failed to download file");
}
} catch (Exception e) {
Log.d("readJSONFeed", e.getLocalizedMessage());
}
return stringBuilder.toString();
}
}
but on this line:
ShortBeerInfoAdapter<ShortBeerInfo> spinnerArrayAdapter = new ArrayAdapter<ShortBeerInfo>(c, android.R.layout.simple_spinner_item,tasteList );
I am getting shortbeerinfoadapter does not have type parameters
my short beer info adapter is:
public class ShortBeerInfoAdapter extends ArrayAdapter<ShortBeerInfo> {
Context context;
int layoutResourceId;
List<ShortBeerInfo> data = null;
public ShortBeerInfoAdapter(Context context, int layoutResourceId, List<ShortBeerInfo> data) {
super(context, layoutResourceId, data);
this.layoutResourceId = layoutResourceId;
this.context = context;
this.data = data;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View row = convertView;
beerHolder holder = null;
if(row == null)
{
LayoutInflater inflater = ((Activity)context).getLayoutInflater();
row = inflater.inflate(layoutResourceId, parent, false);
holder = new beerHolder();
holder.txtBeer = (TextView)row.findViewById(R.id.breweryName);
holder.txtRate = (TextView)row.findViewById(R.id.breweryRate);
holder.txtBar = (RatingBar) row.findViewById(R.id.starbar);
row.setTag(holder);
}
else
{
holder = (beerHolder)row.getTag();
}
ShortBeerInfo beer = data.get(position);
holder.txtBeer.setText(beer.beer);
holder.txtRate.setText(beer.rate + " out of 5.00 Stars");
holder.numHolder= Float.parseFloat(beer.rate);
holder.txtBar.setNumStars(5);
holder.txtBar.setRating(holder.numHolder);
return row;
}
static class beerHolder
{
TextView txtBeer;
TextView txtRate;
RatingBar txtBar;
Float numHolder;
}
}
You have your ShortBeerInfo, which includes the name and ID. You take the beer name, add it to a list of strings, then create the ArrayAdapter from that list. The ArrayAdapter only contains the names.
To get the ID you will need a custom array adapter of type ShortBeerInfo. You'll need to override OnCreateView in the adapter to create the View object for the list item that only contains the beer name. (Or any other beer info you may want to display)
Then in your selection listener getSelectedItem will return a ShortBeerInfo, containing the ID of the selected beer.