How to automatically refresh data in a recycleview android - java

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?!

Related

JVMTI_ERROR_THREAD_NOT_ALIVE error using multiple activites and OpenWeatherMap API

I am making an weather app, on the main screen app shows current weather for a city that is chosen and on the second activity screen you can find weather for next 3 days. I have WeatherInfoTask.java that is used to get JSON for MainActivity and MultipleWeatherTask.java that is used to get JSON for MultipleDays (activity)
so the MainActivity works fine and I get JSON and all of the info is shown on the screen just as it should be, but when I click on the button that should redirect me to the screen of the MultipleDays, I am redirected and just a plain screen is shown without data and this error is shown:
E/StudioProfiler: JVMTI error: 15(JVMTI_ERROR_THREAD_NOT_ALIVE)
These are my files:
public class MainActivity extends AppCompatActivity {
public static String cityName;
Handler handler;
TextView titleText;
TextView temperatureText;
TextView descriptionText;
private boolean isNetworkAvailable() {
ConnectivityManager connectivityManager
= (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
return activeNetworkInfo != null && activeNetworkInfo.isConnected();
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if(!isNetworkAvailable()){
new AlertDialog.Builder(this)
.setIcon(android.R.drawable.ic_dialog_alert)
.setTitle("Closing the App")
.setMessage("No Internet Connection, check your settings")
.setPositiveButton("Close", new DialogInterface.OnClickListener()
{
#Override
public void onClick(DialogInterface dialog, int which) {
finish();
}
})
.show();
}
handler = new Handler();
titleText = (TextView) findViewById(R.id.titleText);
temperatureText = (TextView) findViewById(R.id.temperatureText);
descriptionText = (TextView) findViewById(R.id.descriptionText);
PlaceAutocompleteFragment autocompleteFragment = (PlaceAutocompleteFragment)
getFragmentManager().findFragmentById(R.id.place_autocomplete_fragment);
autocompleteFragment.setHint("Find City");
autocompleteFragment.setOnPlaceSelectedListener(new PlaceSelectionListener() {
#Override
public void onPlaceSelected(Place place) {
cityName = place.getName().toString();
updateWeather(cityName);
/*Log.i(TAG, "Place: " + place.getName());*/
}
#Override
public void onError(Status status) {
// TODO: Handle the error.
Log.i("MainActivity", "An error occurred: " + status);
}
});
}
private void updateWeather(final String city){
new Thread(){
public void run(){
final JSONObject json = WeatherInfoTask.getJSON(MainActivity.this, city);
if(json == null){
Toast.makeText(MainActivity.this, "Error loading weather", Toast.LENGTH_LONG).show();
} else {
handler.post(new Runnable(){
public void run(){
SetWeather(json);
}
});
}
}
}.start();
}
private void SetWeather(JSONObject json){
try {
/*cityField.setText(json.getString("name").toUpperCase(Locale.US) +
", " +
json.getJSONObject("sys").getString("country"));*/
JSONObject details = json.getJSONArray("weather").getJSONObject(0);
JSONObject main = json.getJSONObject("main"); /*"main":{"temp":280.32,"pressure":1012,"humidity":81,"temp_min":279.15,"temp_max":281.15}*/
titleText.setText(R.string.title + cityName);
descriptionText.setText( /*"description":"light intensity drizzle"*/
details.getString("description") +
"\n" + "Humidity: " + main.getString("humidity") + "%" +
"\n" + "Pressure: " + main.getString("pressure") + " hPa");
temperatureText.setText(
String.format("%.2f", main.getDouble("temp"))+ " ℃");
}catch(Exception e){
Log.e("SimpleWeather", "One or more fields not found in the JSON data");
}
}
public void MultipleDays(View view){
Intent intent = new Intent(this, MultipleDays.class);
startActivity(intent);
}
}
Next one:
public class WeatherInfoTask {
private static final String OpenWeatherAPI =
"http://api.openweathermap.org/data/2.5/weather?q=%s&units=metric";
public static JSONObject getJSON(Context context, String city) {
try {
URL url = new URL(String.format(OpenWeatherAPI, city));
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.addRequestProperty("x-api-key", context.getString(R.string.apikey));
BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
StringBuffer json = new StringBuffer(1024);
String tmp = ""; /*tmp = temporary*/
while ((tmp = reader.readLine()) != null)
json.append(tmp).append("\n");
reader.close();
JSONObject data = new JSONObject(json.toString());
/*This value will be 404 if the request was not successful*/
if (data.getInt("cod") != 200) {
/*greska*/
return null;
}
return data;
} catch (Exception e) {
return null;
}
Next one:
public class MultipleDays extends AppCompatActivity {
Handler handler;
TextView day1;
TextView day2;
TextView day3;
Integer dayCounter = 1;
Date comparisonDate;
Date currentDate;
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
Float dailyMin;
Float dailyMax;
Float currMin;
Float currMax;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_multiple_days);
handler = new Handler();
day1 = (TextView) findViewById(R.id.day1);
day2 = (TextView) findViewById(R.id.day2);
day3 = (TextView) findViewById(R.id.day3);
updateMultipleWeather(MainActivity.cityName);
}
private void updateMultipleWeather(final String city){
new Thread(){
public void run(){
final JSONObject json = MultipleWeatherTask.getJSON(MultipleDays.this, city);
if(json == null){
Toast.makeText(MultipleDays.this, "Error loading weather", Toast.LENGTH_LONG).show();
} else {
handler.post(new Runnable(){
public void run(){
setWeather(json);
}
});
}
}
}.start();
}
private void setWeather(JSONObject json){
try {
JSONArray list = json.getJSONArray("list");
for (int i=0; i < list.length() ; i++){
if(i == 0) {
String string = list.getJSONObject(i).getString("dt_txt");
string = convertDate(string);
comparisonDate = formatter.parse(string.replace("",""));
dailyMin = Float.parseFloat(list.getJSONObject(i).getString("temp_min"));
dailyMax = Float.parseFloat(list.getJSONObject(i).getString("temp_max"));
}
else if ( dayCounter <=3 ){
String string = list.getJSONObject(i).getString("dt_txt");
string = convertDate(string);
currentDate = formatter.parse(string.replace("","")); //datum u obliku "yy-MM-dd"
if ( comparisonDate == currentDate ){ //ako smo i dalje na istom danu
currMin = Float.parseFloat(list.getJSONObject(i).getString("temp_min"));
currMax = Float.parseFloat(list.getJSONObject(i).getString("temp_max"));
if( dailyMin > currMin ) dailyMin = currMin;
if( dailyMax < currMax ) dailyMax = currMax;
}
else {
switch (dayCounter){
case 1: day1.setText("Minimum temperature: " + String.format("%.2f", dailyMin) + "\n" +
"Maximum temperature: " + String.format("%.2f", dailyMax) + "\n" +
"Weather: " + list.getJSONObject(i-1).getString("description"));
dayCounter++;
break;
case 2: day2.setText("Minimum temperature: " + String.format("%.2f", dailyMin) + "\n" +
"Maximum temperature: " + String.format("%.2f", dailyMax) + "\n" +
"Weather: " + list.getJSONObject(i-1).getString("description"));
dayCounter++;
break;
case 3: day3.setText("Minimum temperature: " + String.format("%.2f", dailyMin) + "\n" +
"Maximum temperature: " + String.format("%.2f", dailyMax) + "\n" +
"Weather: " + list.getJSONObject(i-1).getString("description"));
dayCounter++;
break;
}
}
}
}
Next one:
public class MultipleWeatherTask {
private static final String OpenWeatherAPI =
"api.openweathermap.org/data/2.5/forecast?q=%s&units=metric";
public static JSONObject getJSON(Context context, String city) {
try {
URL url = new URL(String.format(OpenWeatherAPI, city));
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.addRequestProperty("x-api-key", context.getString(R.string.apikey));
BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
StringBuffer json = new StringBuffer(1024);
String tmp = ""; /*tmp = temporary*/
while ((tmp = reader.readLine()) != null)
json.append(tmp).append("\n");
reader.close();
JSONObject data = new JSONObject(json.toString());
/*This value will be 404 if the request was not successful*/
if (data.getInt("cod") != 200) {
/*greska*/
return null;
}
return data;
} catch (Exception e) {
return null;
}
}
}
File ---> Invalidate Caches / Restart will help you.

JAVA, ANDROID: setImageResource(int) not displaying image

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...

Unable to fetch images in Grid view

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. :)

IndexOutOfBound exception While Scrolling down in ListView during pullToRefresh

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.

how do i pass user-defined array parameter to asynctask in android

However, when i just check the user-defined array parameter, customerList in the outer class there are values inside but the uploadAsyncTask innerclass keeps failing on the emulator (displaying unfortunately the app has failed).
private ArrayList<CustomerData> customerList = new ArrayList<CustomerData>();
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
db = new DBAdapter(this);
presidents = getResources().getStringArray(R.array.presidents_array);
client = new AsyncHttpClient();
Button btn_Save, btn_Backup;
btn_Save = (Button) findViewById(R.id.btnSave);
btn_Backup = (Button) findViewById(R.id.btnBackup);
txt_AcctNum = (TextView) findViewById(R.id.txtAcctNum);
txt_AcctName = (TextView) findViewById(R.id.txtAcctName);
s1 = (Spinner) findViewById(R.id.spinner);
txt_Amt = (TextView) findViewById(R.id.txtAmt);
/*
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
android.R.layout.simple_spinner_item, presidents);
*/
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_single_choice, presidents);
s1.setAdapter(adapter);
s1.setOnItemSelectedListener(new OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> arg0,
View arg1, int arg2, long arg3) {
int index = arg0.getSelectedItemPosition();
//Toast.makeText(getBaseContext(),
// "You have selected item : " + presidents[index],
// Toast.LENGTH_SHORT).show();
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
}
});
-------other codes here----
btn_Backup.setOnClickListener(new Button.OnClickListener() {
#SuppressWarnings(value = "unchecked")
public void onClick(View view) {
ArrayList<CustomerData> custList = new ArrayList<CustomerData>();
// db = new DBAdapter(context);
db.open();
//db.backupToSD();
//---get all contacts---
Cursor c = db.getAllCustomers();
if (c.moveToFirst()) {
do {
//DisplayContact(c);
//sendData();
custList = addAndDisplayCustomer(c);
} while (c.moveToNext());
}
/* for (int i = 0; i < custList.size(); i++) {
Toast.makeText(getApplicationContext(), "---Customer Data--- " + "id: " +
custList.get(i).getId() + " Acct Name: " +
custList.get(i).getAcctName() + " Acct Num: " +
custList.get(i).getAcctNum() + " Tnx type: " +
custList.get(i).getTxnType() + " Amt: " +
custList.get(i).getAmt(), Toast.LENGTH_LONG).show(); }*/
Toast.makeText(getApplicationContext(), " Uploading data ... " + custList.get(0).getId(), Toast.LENGTH_LONG).show();
UploadASyncTask upload = new UploadASyncTask();
upload.execute(custList);
}
public ArrayList<CustomerData> addAndDisplayCustomer(Cursor c)
{
CustomerData customer = new CustomerData(c.getString(0), c.getString(1),
c.getString(2), c.getString(3), c.getString(4));
customerList.add(customer);
return customerList;
}
//int delRows = db.deleteAll();
//db.backupToSD();
//db.dropTable();
//Toast.makeText(getApplicationContext(), " Table successfully dropped ! ", Toast.LENGTH_LONG).show();
//db.close();
});
}
private class UploadASyncTask extends AsyncTask<ArrayList<CustomerData>, Void, Void> {
private Cursor c;
private String id;
private String acct_Name ;
private String acct_Num;
private String txnType;
private String amt;
//private ArrayList<CustomerData> custList;
private Context mContext1;
private ProgressDialog dialog = null;
private Context mContext = null;
#Override
protected void onPreExecute() {
dialog = new ProgressDialog(MainActivity.this);
dialog.setTitle(" Sending to the server... ");
dialog.setMessage("Please wait...");
dialog.setProgressDrawable(mContext.getWallpaper());
dialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
dialog.setCancelable(false);
dialog.show();
}
#Override
#SafeVarargs
final protected Void doInBackground(ArrayList<CustomerData>... custList) {
try {
ArrayList<CustomerData> custom = custList[0];
for (int i = 0; i<custom.size(); i++) {
String id = custom.get(i).getId();
String acct_Name = custom.get(i).getAcctName();
String acct_Num = custom.get(i).getAcctNum();
String txnType = custom.get(i).getTxnType();
String amt = custom.get(i).getAmt();
/*runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(getApplicationContext(), "Welcome guy: " + id,
Toast.LENGTH_LONG).show();
}
});*/
HttpParams params = new BasicHttpParams();
HttpClient httpclient = new DefaultHttpClient(params);
HttpPost httpPost = new HttpPost
("http://10.0.2.2:8080/RestWebService/rest/customer");
List<NameValuePair> postParams = new ArrayList<NameValuePair>();
postParams.add(new BasicNameValuePair("id", id));
postParams.add(new BasicNameValuePair("acct_name", acct_Name));
postParams.add(new BasicNameValuePair("acct_num", acct_Num));
postParams.add(new BasicNameValuePair("txn_type", txnType));
postParams.add(new BasicNameValuePair("amt", amt));
UrlEncodedFormEntity entity = new UrlEncodedFormEntity(postParams);
entity.setContentEncoding(HTTP.UTF_8);
httpPost.setEntity(entity);
HttpResponse httpResponse = httpclient.execute(httpPost);
InputStream inputStream = httpResponse.getEntity().getContent();
String result = "";
id = "";
acct_Name = "";
acct_Num = "";
txnType = "";
amt = "";
}
}
catch (Exception e)
{
Log.e("Server Error: ",e.getMessage());
}
return null;
}
#Override
protected void onPostExecute(Void result) {
//custList.clear();
dialog.dismiss();
}
}
}
When I saw your code : there is a little problem. I don't know it's the good answer but :
private Context mContext = null;
and
dialog.setProgressDrawable(mContext.getWallpaper());
It's a nullPointerException in this line
For me You can delete the context and the cursor on your AsyncTask. Create a constructor on your AsyncTask and put the context in parameters, use it for the progressDialog
Hope it's help

Categories