I am trying to parse some data from server and compare the data with the data in the database...
Everything seems working fine... except I am getting only same value even the comparing data change... I'll explain it with the code...
In the below code, there is textviews tv3 and tv4... even the comparing data ie, shopid changed, it shows the value from the first array of the json...
when i tried to debug, i found the the run() inside the runOnUithread is calling after 2-3 loops... i donno whats happening here... Please somone help ,e to sort out the issue...
Edit: while debugging when i skip to each line it not showing any error...
But when i try to skip to the breakpoints using F9 it shows the error...
Edit: 2: Since the code is litle bit long, i juz deleted som unwanted part...
private Bitmap downloadBitmap(String url) {
HttpURLConnection urlConnection = null;
try {
URL uri = new URL(url);
urlConnection = (HttpURLConnection) uri.openConnection();
int statusCode = urlConnection.getResponseCode();
if (statusCode != HttpStatus.SC_OK) {
return null;
}
InputStream inputStream = urlConnection.getInputStream();
if (inputStream != null) {
bitmap = BitmapFactory.decodeStream(inputStream);
return bitmap;
}
} catch (Exception e) {
urlConnection.disconnect();
Log.w("ImageDownloader", "Error downloading image from " + url);
} finally {
if (urlConnection != null) {
urlConnection.disconnect();
}
}
return null;
}
#Override
public void onResume() {
mapView.onResume();
super.onResume();
}
#Override
public void onDestroy() {
super.onDestroy();
mapView.onDestroy();
}
#Override
public void onLowMemory() {
super.onLowMemory();
mapView.onLowMemory();
}
private class GetJsondata extends AsyncTask<Void, Void, String> {
#Override
protected void onPreExecute() {
dialog = ProgressDialog.show(getActivity(), "", getActivity().getResources().getString(R.string.pleasewait), true);
}
#Override
protected String doInBackground(Void... arg0) {
// Creating service handler class instance
ConnectivityManager conMgr = (ConnectivityManager) getActivity().getSystemService(Context.CONNECTIVITY_SERVICE);
activeNetwork = conMgr.getActiveNetworkInfo();
if (activeNetwork != null && activeNetwork.isConnected()) {
ServiceHandler sh = new ServiceHandler();
// Making a request to url and getting response
String jsonStr = sh.makeServiceCall(url, ServiceHandler.GET);
Log.d("Response: ", "> " + jsonStr);
if (jsonStr != null) {
try {
jsonObj = new JSONObject(jsonStr);
ObjectOutput out = new ObjectOutputStream(new FileOutputStream
(new File(getActivity().getCacheDir(), "") + File.separator + "cacheFile.srl"));
out.writeObject(jsonObj.toString());
out.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
} else {
Log.e("ServiceHandler", "Couldn't get any data from the url");
}
} else {
try {
ObjectInputStream in = new ObjectInputStream(new FileInputStream
(new File(getActivity().getCacheDir() + File.separator + "cacheFile.srl")));
jsonObj = new JSONObject((String) in.readObject());
in.close();
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (OptionalDataException e) {
e.printStackTrace();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (StreamCorruptedException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
}
if (jsonObj != null) {
try {
ofrList = new ArrayList<ArrayList<String>>();
// Getting JSON Array node
jsonArray = jsonObj.getJSONArray("offers");
shoplistarray = new ArrayList<ArrayList<String>>();
// looping through All Contacts
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject c = jsonArray.getJSONObject(i);
url1 = c.getString("url");
if (userPrefs.getString("locale", null) == null || userPrefs.getString("locale", null).equals("en")) {
desc = c.getString("desc");
} else {
desc = c.getString("desc_ar");
}
expdate = c.getString("expdate");
ofrdate = c.getString("date");
shopsarray = c.getJSONArray("shops");
for (int n = 0; n < shopsarray.length(); n++) {
JSONObject jobj = shopsarray.getJSONObject(n);
shopid = jobj.getString("shopid");
if (shopid.equals(id) && tv3.getText().toString().equals("") ) {
downloadBitmap(url1);
finalI = i;
getActivity().runOnUiThread(new Runnable() {
public void run() {
if (activeNetwork != null && activeNetwork.isConnected()) {
image.setImageBitmap(bitmap);
saveFileInCache(String.valueOf(finalI), bitmap);
} else {
getFileOutOfCache(String.valueOf(finalI));
image.setImageBitmap(bitmap);
}
tv3.setText(desc);
tv4.setText(getActivity().getResources().getString(R.string.validtill) + expdate);
}
});
}
}
}
} catch (JSONException e) {
e.printStackTrace();
}
} else {
getActivity().runOnUiThread(new Runnable() {
public void run() {
Toast.makeText(getActivity(), getActivity().getResources().getString(R.string.urnotconnected), Toast.LENGTH_LONG).show();
}
});
}
return desc;
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
dialog.dismiss();
}
}
private Bitmap getFileOutOfCache(String fileName) {
final String cachePath = getActivity().getCacheDir().getPath();
File myDiskCacheFilePath = new File(cachePath);
File myCachedFile = new File(myDiskCacheFilePath
+ File.separator + fileName);
if (myCachedFile.exists()) {
bitmap = BitmapFactory.decodeFile(myCachedFile.toString());
} else {
Toast.makeText(getActivity(), getActivity().getResources().getString(R.string.cachedfilenotexist), Toast.LENGTH_LONG).show();
}
return bitmap;
}
public void saveFileInCache(String aFileName, Bitmap myImage) {
final String cachePath = getActivity().getCacheDir().getPath();
File myDiscCacheFilePath;
myDiscCacheFilePath = new File(cachePath);
File myDiscCacheFile = new File(myDiscCacheFilePath + File.separator + aFileName);
try {
FileOutputStream out = new FileOutputStream(myDiscCacheFile);
myImage.compress(Bitmap.CompressFormat.JPEG, 80, out);
out.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
Toast.makeText(getActivity(), getActivity().getResources().getString(R.string.cachefailed), Toast.LENGTH_SHORT).show();
} catch (IOException e) {
e.printStackTrace();
}
}
}
private Bitmap downloadBitmap(String url) {
HttpURLConnection urlConnection = null;
try {
URL uri = new URL(url);
urlConnection = (HttpURLConnection) uri.openConnection();
int statusCode = urlConnection.getResponseCode();
if (statusCode != HttpStatus.SC_OK) {
return null;
}
InputStream inputStream = urlConnection.getInputStream();
if (inputStream != null) {
bitmap = BitmapFactory.decodeStream(inputStream);
return bitmap;
}
} catch (Exception e) {
urlConnection.disconnect();
Log.w("ImageDownloader", "Error downloading image from " + url);
} finally {
if (urlConnection != null) {
urlConnection.disconnect();
}
}
return null;
}
#Override
public void onResume() {
mapView.onResume();
super.onResume();
}
#Override
public void onDestroy() {
super.onDestroy();
mapView.onDestroy();
}
#Override
public void onLowMemory() {
super.onLowMemory();
mapView.onLowMemory();
}
private class GetJsondata extends AsyncTask<Void, Void, String> {
boolean isIfCondition=false;
#Override
protected void onPreExecute() {
dialog = ProgressDialog.show(getActivity(), "", getActivity().getResources().getString(R.string.pleasewait), true);
}
#Override
protected String doInBackground(Void... arg0) {
// Creating service handler class instance
ConnectivityManager conMgr = (ConnectivityManager) getActivity().getSystemService(Context.CONNECTIVITY_SERVICE);
activeNetwork = conMgr.getActiveNetworkInfo();
if (activeNetwork != null && activeNetwork.isConnected()) {
ServiceHandler sh = new ServiceHandler();
// Making a request to url and getting response
String jsonStr = sh.makeServiceCall(url, ServiceHandler.GET);
Log.d("Response: ", "> " + jsonStr);
if (jsonStr != null) {
try {
jsonObj = new JSONObject(jsonStr);
ObjectOutput out = new ObjectOutputStream(new FileOutputStream
(new File(getActivity().getCacheDir(), "") + File.separator + "cacheFile.srl"));
out.writeObject(jsonObj.toString());
out.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
} else {
Log.e("ServiceHandler", "Couldn't get any data from the url");
}
} else {
try {
ObjectInputStream in = new ObjectInputStream(new FileInputStream
(new File(getActivity().getCacheDir() + File.separator + "cacheFile.srl")));
jsonObj = new JSONObject((String) in.readObject());
in.close();
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (OptionalDataException e) {
e.printStackTrace();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (StreamCorruptedException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
}
if (jsonObj != null) {
try {
ofrList = new ArrayList<ArrayList<String>>();
// Getting JSON Array node
jsonArray = jsonObj.getJSONArray("offers");
shoplistarray = new ArrayList<ArrayList<String>>();
// looping through All Contacts
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject c = jsonArray.getJSONObject(i);
url1 = c.getString("url");
if (userPrefs.getString("locale", null) == null || userPrefs.getString("locale", null).equals("en")) {
desc = c.getString("desc");
} else {
desc = c.getString("desc_ar");
}
expdate = c.getString("expdate");
ofrdate = c.getString("date");
shopsarray = c.getJSONArray("shops");
for (int n = 0; n < shopsarray.length(); n++) {
JSONObject jobj = shopsarray.getJSONObject(n);
shopid = jobj.getString("shopid");
if (shopid.equals(id) && tv3.getText().toString().equals("") ) {
downloadBitmap(url1);
finalI = i;
//no need to use runonuithread since post execute methods already runs on main ui thread ..rather set isIfCondition=true and do this job on postexecute method
isIfCondition=true;
desc1=desc;
expdate1=expdate;
/*getActivity().runOnUiThread(new Runnable() {
public void run() {
if (activeNetwork != null && activeNetwork.isConnected()) {
image.setImageBitmap(bitmap);
saveFileInCache(String.valueOf(finalI), bitmap);
} else {
getFileOutOfCache(String.valueOf(finalI));
image.setImageBitmap(bitmap);
}
tv3.setText(desc);
tv4.setText(getActivity().getResources().getString(R.string.validtill) + expdate);
}
});*/
}
}
}
} catch (JSONException e) {
e.printStackTrace();
}
} else {
//no need to use runonuithread since post execute methods already runs on main ui thread
/*getActivity().runOnUiThread(new Runnable() {
public void run() {
Toast.makeText(getActivity(), getActivity().getResources().getString(R.string.urnotconnected), Toast.LENGTH_LONG).show();
}
});*/
}
return desc;
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
dialog.dismiss();
if(isIfCondition=true)
{
if (activeNetwork != null && activeNetwork.isConnected()) {
image.setImageBitmap(bitmap);
saveFileInCache(String.valueOf(finalI), bitmap);
} else {
getFileOutOfCache(String.valueOf(finalI));
image.setImageBitmap(bitmap);
}
tv3.setText(desc1);
tv4.setText(getActivity().getResources().getString(R.string.validtill) + expdate1);
}
}
}
private Bitmap getFileOutOfCache(String fileName) {
final String cachePath = getActivity().getCacheDir().getPath();
File myDiskCacheFilePath = new File(cachePath);
File myCachedFile = new File(myDiskCacheFilePath
+ File.separator + fileName);
if (myCachedFile.exists()) {
bitmap = BitmapFactory.decodeFile(myCachedFile.toString());
} else {
Toast.makeText(getActivity(), getActivity().getResources().getString(R.string.cachedfilenotexist), Toast.LENGTH_LONG).show();
}
return bitmap;
}
public void saveFileInCache(String aFileName, Bitmap myImage) {
final String cachePath = getActivity().getCacheDir().getPath();
File myDiscCacheFilePath;
myDiscCacheFilePath = new File(cachePath);
File myDiscCacheFile = new File(myDiscCacheFilePath + File.separator + aFileName);
try {
FileOutputStream out = new FileOutputStream(myDiscCacheFile);
myImage.compress(Bitmap.CompressFormat.JPEG, 80, out);
out.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
Toast.makeText(getActivity(), getActivity().getResources().getString(R.string.cachefailed), Toast.LENGTH_SHORT).show();
} catch (IOException e) {
e.printStackTrace();
}
}
there is not need to use runonuithread or any other thread...because asynctask is already do this for you..doinbackground work run on bgthread and onpostexecute work on mainuithread..
Just check the code...i haven't check..but it will work for sure....
ConnectivityManager conMgr = (ConnectivityManager) getActivity().getSystemService(Context.CONNECTIVITY_SERVICE);
activeNetwork = conMgr.getActiveNetworkInfo();
if (activeNetwork != null && activeNetwork.isConnected()) {
new GetJsondata().execute()
}else{
//show toast
}
Write the above code in the place where you are calling the asynctask.Remove it from the asynctask itself.
Related
I have two AppCompatActivitys, both should have an onItemClickListener, but one of them doesn't do anything on click. I've just added a Toast for test reason, later on it should call a function to delete an item from list (with an ajax request)
What am I doing wrong?
I have made custom list and custom adapter for this - I know, I am new to Android Studio, but the other Activity works fine, and I cant find any differences.
public class ActivityListofProducts extends AppCompatActivity {
ProgressDialog pd;
SharedPreferences preferences;
String userid;
String session;
String list_id = "-1"; // or other values
String appVersion = "";
private ArrayList<listProductItem> myProducts = new ArrayList<listProductItem>();
private ArrayList<listProductItem> groceryFilterProducts = new ArrayList<listProductItem>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
handleIntent(getIntent());
setContentView(R.layout.activity_list_of_products);
this.setTitle(getString(R.string.grocery_list));
Bundle b = getIntent().getExtras();
SwipeRefreshLayout swipeRefreshLayout = (SwipeRefreshLayout) findViewById(R.id.refreshLayout);
if (b != null)
list_id = b.getString("list_id");
Toast.makeText(this, "List to open " + " " + list_id, Toast.LENGTH_SHORT).show();
preferences =
getSharedPreferences(this.getPackageName(), this.MODE_PRIVATE);
userid = preferences.getString("userid", "");
session = preferences.getString("session", "");
appVersion = preferences.getString("appVersion", "");
getData();
swipeRefreshLayout.setOnRefreshListener(
new SwipeRefreshLayout.OnRefreshListener() {
#Override
public void onRefresh() {
getData();
swipeRefreshLayout.setRefreshing(false);
}
}
);
}
public void getData() {
AsyncTask<String, String, String> Task_GetListofProducts = new Task_GetListofProducts();
Task_GetListofProducts.execute("https://get-some-json.com");
}
public void initListofProducts(String jsonString) {
Log.i("jsonString",jsonString);
try {
JSONObject jsonResponse = new JSONObject(jsonString);
JSONObject jsonListMode = jsonResponse.getJSONObject("list");
String ListName = jsonListMode.optString("name");
this.setTitle(ListName);
JSONArray jsonMainNode = jsonResponse.optJSONArray("data");
for (int i = 0; i < jsonMainNode.length(); i++) {
JSONObject jsonChildNode = jsonMainNode.getJSONObject(i);
int item_amount = jsonChildNode.optInt("item_amount");
int id = jsonChildNode.optInt("id");
String item_name = jsonChildNode.optString("item_name",">Name<");
int done = jsonChildNode.optInt("done", 0);
String timestamp = jsonChildNode.optString("timestamp", "");
String item_scale = jsonChildNode.optString("item_scale", "x");
String img = jsonChildNode.optString("img", "x");
double bestprice = jsonChildNode.optDouble("bestprice");
//int oitems = jsonChildNode.optInt("oitems", 0);
//int shared = jsonChildNode.optInt("shared", 0);
String outPut = "item_amount:"+ item_amount +" id:"+ id +" item_name:"+ item_name +" done:"+ done +" timestamp:"+ timestamp +" item_scale:"+ item_scale +" img:"+ img;
Log.i("outPut",outPut);
myProducts.add(new listProductItem(id, item_name, item_amount, item_scale, img, done, timestamp, bestprice));
}
final ListView lv = findViewById(R.id.grocery_list_of_products);
lv.setAdapter(new listofProductsAdapter(this, myProducts));
lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> a, View v, int position, long id) {
/*
!! HERE is my problem. This Code seems not to be executed !!
*/
Toast.makeText(ActivityListofProducts.this, "Should handle click now.", Toast.LENGTH_SHORT).show();
}
});
} catch (JSONException e) {
Toast.makeText(getApplicationContext(), "Error" + e.toString(), Toast.LENGTH_SHORT).show();
}
}
public void setProductDone(int pid, int done) {
String url = "put-some-json.com";
new ActivityListofProducts.Task_SetProductDone().execute(url);
}
private class Task_SetProductDone extends AsyncTask<String, String, String> {
protected void onPreExecute() {
super.onPreExecute();
pd = new ProgressDialog(ActivityListofProducts.this);
pd.setMessage("Please wait");
pd.setCancelable(false);
pd.show();
}
protected String doInBackground(String... params) {
HttpURLConnection connection = null;
BufferedReader reader = null;
Log.i("doInBackground",params.toString());
try {
URL url = new URL(params[0]);
connection = (HttpURLConnection) url.openConnection();
connection.connect();
InputStream stream = connection.getInputStream();
reader = new BufferedReader(new InputStreamReader(stream));
StringBuffer buffer = new StringBuffer();
String line = "";
while ((line = reader.readLine()) != null) {
buffer.append(line + "\n");
Log.d("Response: ", "> " + line); //here you will get whole response...... :-)
}
return buffer.toString();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (UnknownHostException e) {
Toast.makeText(ActivityListofProducts.this, "No Internet?", Toast.LENGTH_SHORT).show();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (connection != null) {
connection.disconnect();
}
try {
if (reader != null) {
reader.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
return null;
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
if (pd.isShowing()) {
pd.dismiss();
}
Log.i("onPostExecute", result);
}
}
private class Task_GetListofProducts extends AsyncTask<String, String, String> {
protected void onPreExecute() {
super.onPreExecute();
pd = new ProgressDialog(ActivityListofProducts.this);
pd.setMessage("Please wait");
pd.setCancelable(false);
pd.show();
myProducts = new ArrayList<listProductItem>(); //empty list
}
protected String doInBackground(String... params) {
HttpURLConnection connection = null;
BufferedReader reader = null;
Log.i("doInBackground",params.toString());
try {
URL url = new URL(params[0]);
connection = (HttpURLConnection) url.openConnection();
connection.connect();
InputStream stream = connection.getInputStream();
reader = new BufferedReader(new InputStreamReader(stream));
StringBuffer buffer = new StringBuffer();
String line = "";
while ((line = reader.readLine()) != null) {
buffer.append(line + "\n");
Log.d("Response: ", "> " + line); //here you will get whole response...... :-)
}
return buffer.toString();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (connection != null) {
connection.disconnect();
}
try {
if (reader != null) {
reader.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
return null;
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
if (pd.isShowing()) {
pd.dismiss();
}
initListofProducts(result);
}
}
private class Task_FindProducts extends AsyncTask<String, String, String> {
protected void onPreExecute() {
super.onPreExecute();
pd = new ProgressDialog(ActivityListofProducts.this);
pd.setMessage("Please wait");
pd.setCancelable(false);
pd.show();
myProducts = new ArrayList<listProductItem>(); //empty list
}
protected String doInBackground(String... params) {
HttpURLConnection connection = null;
BufferedReader reader = null;
Log.i("doInBackground",params.toString());
try {
URL url = new URL(params[0]);
connection = (HttpURLConnection) url.openConnection();
connection.connect();
InputStream stream = connection.getInputStream();
reader = new BufferedReader(new InputStreamReader(stream));
StringBuffer buffer = new StringBuffer();
String line = "";
while ((line = reader.readLine()) != null) {
buffer.append(line + "\n");
Log.d("Response: ", "> " + line); //here you will get whole response...... :-)
}
return buffer.toString();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (connection != null) {
connection.disconnect();
}
try {
if (reader != null) {
reader.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
return null;
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
if (pd.isShowing()) {
pd.dismiss();
}
setFilterProducts(result);
}
}
}
I have this piece of code on android that reads data from Assets folder, so I need from this code to read data from external like dropbox. Ho to change and read data from dropbox. thanks
#Override
protected RadioDatas doInBackground(Void... params) {
BufferedReader reader = null;
ArrayList<RadioData> radioDatas = new ArrayList<>();
RadioDatas datas = new RadioDatas();
try {
reader = new BufferedReader(
new InputStreamReader(context.getAssets().open("url.txt"), "Unicode"));
String mLine;
while ((mLine = reader.readLine()) != null) {
RadioData radioData = new RadioData();
String[] meta = mLine.split(";");
radioData.setUrl(meta[0]);
radioData.setTitle(meta[1]);
radioData.setGenres(meta[2]);
radioDatas.add(radioData);
}
} catch (IOException e) {
//log the exception
return null;
} finally {
if (reader != null) {
try {
reader.close();
} catch (IOException e) {
//log the exception
}
}
}
datas.setRadioDatas(radioDatas);
return datas;
}
This would work....
public class Execute extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected Void doInBackground(Void... arg0) {
HttpHandler handler = new HttpHandler();
String jsonString = handler.makeServiceCall(json);
if (jsonString != null) {
try {
//parse jsonString
} catch (JSONException e) {
Log.i("Error with parsing", e.getMessage());
}
}
return null;
}
protected void onPostExecute(Void result) {
super.onPostExecute(result);
}
}
You will need a HTTPHandler class...
public class HttpHandler {
private static final String TAG = HttpHandler.class.getSimpleName();
public HttpHandler() {
}
public String makeServiceCall(String reqUrl) {
String response = null;
try {
URL url = new URL(reqUrl);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
// read the response
InputStream in = new BufferedInputStream(conn.getInputStream());
response = convertStreamToString(in);
in.close();
} catch (MalformedURLException e) {
Log.e(TAG, "MalformedURLException: " + e.getMessage());
} catch (ProtocolException e) {
Log.e(TAG, "ProtocolException: " + e.getMessage());
} catch (IOException e) {
Log.e(TAG, "IOException: " + e.getMessage());
} catch (Exception e) {
Log.e(TAG, "Exception: " + e.getMessage());
}
return response;
}
private String convertStreamToString(InputStream is) {
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
StringBuilder sb = new StringBuilder();
String line;
try {
while ((line = reader.readLine()) != null) {
sb.append(line).append('\n');
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return sb.toString();
}
}
To run it.
new Execute().execute;
I'm trying to use AsyncTaskLoader to retrieve data then parse the resulting json file, however, I can't figure out why I keep getting a
return null;
instead of returning
return gameList;
DailyScheduleFragment.java
Method calling the Loader:
public void loadGameScheduleList() {
getLoaderManager().initLoader(LOADER_ID_DAILY_SCHEDULE, null, new LoaderCallbacks<ArrayList<Game>>() {
public Loader<ArrayList<Game>> onCreateLoader(int id, Bundle args) {
return new DailyScheduleLoader(DailyScheduleFragment.this.getContext());
}
public void onLoadFinished(Loader<ArrayList<Game>> loader, ArrayList<Game> data) {
if (data == null) {
Exception exception = ((DailyScheduleLoader) loader).getException();
if (exception == null) {
return;
}
if (exception instanceof NoNetworkException) {
DailyScheduleFragment.this._btnMessage.setText(R.string.general_msg_no_network_connection_turn_on);
DailyScheduleFragment.this._btnMessage.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Intents.networkSettings(DailyScheduleFragment.this.getContext());
}
});
DailyScheduleFragment.this._progressBar.setVisibility(View.GONE);
DailyScheduleFragment.this._btnMessage.setVisibility(View.GONE);
return;
}
DailyScheduleFragment.this._btnMessage.setText(R.string.general_msg_something_went_wrong);
DailyScheduleFragment.this._btnMessage.setOnClickListener(null);
DailyScheduleFragment.this._progressBar.setVisibility(View.GONE);
DailyScheduleFragment.this._btnMessage.setVisibility(View.GONE);
return;
}
DailyScheduleFragment.this._games.clear();
Iterator it = data.iterator();
while (it.hasNext()) {
DailyScheduleFragment.this._games.add((Game) it.next());
}
DailyScheduleFragment.this._adapter.notifyDataSetChanged();
DailyScheduleFragment.this.displayListState();
}
public void onLoaderReset(Loader<ArrayList<Game>> loader) {
}
}).forceLoad();
}
DailyScheduleLoader.java
public class DailyScheduleLoader extends AsyncTaskLoader<ArrayList<Game>> {
private Context _context;
private Exception _exception;
public DailyScheduleLoader(Context context) {
super(context);
this._context = context;
}
public ArrayList<Game> loadInBackground() {
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this._context);
try {
ArrayList<Game> gameList = Parse.gameList(Networking.sendHttpRequest("http://api.sportradar.us/nhl/trial/v5/en/games/2018/01/01/schedule.json?api_key=xxx", this._context));
return gameList;
} catch (Exception e) {
this._exception = e;
return null;
} catch (Throwable throwable) {
throwable.printStackTrace();
}
return null;
}
public Exception getException() {
return this._exception;
}
Network class:
public static final class Networking {
public static String sendHttpRequest(String urlString, Context context) throws Throwable {
NoNetworkException e;
Exception ex;
Throwable th;
if (urlString == null || urlString.trim().equals(BuildConfig.FLAVOR)) {
throw new NullPointerException("urlString");
}
HttpURLConnection httpCon = null;
InputStream input_stream = null;
InputStreamReader input_stream_reader = null;
BufferedReader input = null;
StringBuilder response = new StringBuilder();
try {
if (isNetworkAvailable(context)) {
httpCon = (HttpURLConnection) new URL(urlString).openConnection();
if (httpCon.getResponseCode() != 200) {
Log.e("TAG", "Cannot Connect to : " + urlString);
if (input == null) {
return null;
}
try {
input_stream_reader.close();
input_stream.close();
input.close();
} catch (IOException e2) {
e2.printStackTrace();
}
if (httpCon == null) {
return null;
}
httpCon.disconnect();
return null;
}
input_stream = httpCon.getInputStream();
InputStreamReader input_stream_reader2 = new InputStreamReader(input_stream);
try {
BufferedReader input2 = new BufferedReader(input_stream_reader2);
while (true) {
try {
String line = input2.readLine();
if (line == null) {
break;
}
response.append(line).append("\n");
} catch (Exception e4) {
ex = e4;
input = input2;
input_stream_reader = input_stream_reader2;
} catch (Throwable th2) {
th = th2;
input = input2;
input_stream_reader = input_stream_reader2;
}
}
if (input2 != null) {
try {
input_stream_reader2.close();
input_stream.close();
input2.close();
} catch (IOException e22) {
e22.printStackTrace();
}
if (httpCon != null) {
httpCon.disconnect();
input = input2;
input_stream_reader = input_stream_reader2;
return response.toString();
}
}
input_stream_reader = input_stream_reader2;
} catch (Exception e6) {
ex = e6;
input_stream_reader = input_stream_reader2;
ex.printStackTrace();
if (input != null) {
try {
input_stream_reader.close();
input_stream.close();
input.close();
} catch (IOException e222) {
e222.printStackTrace();
}
if (httpCon != null) {
httpCon.disconnect();
}
}
return response.toString();
} catch (Throwable th4) {
th = th4;
input_stream_reader = input_stream_reader2;
if (input != null) {
try {
input_stream_reader.close();
input_stream.close();
input.close();
} catch (IOException e2222) {
e2222.printStackTrace();
}
if (httpCon != null) {
httpCon.disconnect();
}
}
throw th;
}
return response.toString();
}
throw new NoNetworkException();
} catch (NoNetworkException e7) {
e = e7;
throw e;
} catch (Exception e8) {
ex = e8;
ex.printStackTrace();
if (input != null) {
input_stream_reader.close();
input_stream.close();
input.close();
if (httpCon != null) {
httpCon.disconnect();
}
}
return response.toString();
}
}
public static boolean isNetworkAvailable(#NonNull Context context) {
#SuppressLint("WrongConstant") NetworkInfo activeNetworkInfo = ((ConnectivityManager) context.getSystemService("connectivity")).getActiveNetworkInfo();
return activeNetworkInfo != null && activeNetworkInfo.isConnected();
}
}
Parse class:
public static class Parse {
public static ArrayList<Game> gameList(String json) throws JSONException {
ArrayList<Game> games = new ArrayList();
JSONArray results = new JSONObject(json).getJSONArray("games");
// looping through All Games
for (int i = 0; i < results.length(); i++) {
JSONObject gameJSON = results.getJSONObject(i);
Game game = new Game();
game.setId(gameJSON.getString(Responses.Games.VALUE_ID));
game.setStatus(gameJSON.getString(Responses.Games.VALUE_STATUS));
games.add(game);
}
return games;
}
}
I found the code on a website and trying to modify it to suit my needs. For the most part, it works well, except I can't figure out where I'm going wrong with this.
If it helps, here's the json file that's returned in the request (sorry about the formatting):
{"date":"2018-01-01","league":{"id":"fd560107-a85b-4388-ab0d-655ad022aff7","name":"NHL","alias":"NHL"},"games":[{"id":"6d20bdbd-b5e0-46ab-8b98-45ea01ab0e2b","status":"scheduled","coverage":"full","scheduled":"2018-01-01T18:00:00+00:00","reference":"20601","venue":{"id":"faebd24e-ccfb-4e7c-aa58-1dee9e82bb0f","name":"Citi Field","capacity":45000,"address":"123 Roosevelt Ave","city":"Queens","state":"NY","zip":"11368","country":"USA","time_zone":"US/Eastern"},"broadcast":{"network":"NBC"},"home":{"id":"4416d559-0f24-11e2-8525-18a905767e44","name":"Buffalo Sabres","alias":"BUF"},"away":{"id":"441781b9-0f24-11e2-8525-18a905767e44","name":"New York Rangers","alias":"NYR"}}]}
Go here if you want it formatted.
I've added break points and stepped through the code to check the variables. All seems right, up until the
return gameList;
After execution for 5 to 6 times i am not able to get response and the message is also not going to gateway and the application get struck.At InputStreamReader i am not able to get any response after execution for 5 times.When i checked the logs no error is coming but the Input Stream is not printing.
XMLFunctions.java
public static String getLocalCurtainControlResponse( String ipadress, String imvgid, String deviceid, String command, String value, int slidedValue) {
String result = null;
BufferedReader reader =null;
System.out.println("getLocalCurtainControlResponse : IN");
System.out.println("command : " + command);
System.out.println("value : " + value);
byte[] loginBytes = ("admin" + ":" + "admin").getBytes();
StringBuilder loginBuilder = new StringBuilder()
.append("Basic ")
.append(Base64.encodeToString(loginBytes, Base64.DEFAULT));
try {
URL url = new URL("http://" + ipadress + "/cgi-bin/WebInterface.cgi?ImvgId=" + imvgid + "%20&DeviceId=" + deviceid + "%20&Action=" + command + "%20&Value=" + value + "%20&Level=" + slidedValue + "%20&App=MID");
System.out.print("step0"+"http://" + ipadress + "/cgi-bin/WebInterface.cgi?ImvgId=" + imvgid + "%20&DeviceId=" + deviceid + "%20&Action=" + command + "%20&Value=" + value + "%20&Level=" + slidedValue + "%20&App=MID");
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
// connection.setRequestMethod("GET");
connection.addRequestProperty("Authorization", loginBuilder.toString());
// connection.connect();
InputStream in = connection.getInputStream();
System.out.print("step1"+connection);
StringBuilder sb = new StringBuilder();
System.out.print("step2"+sb);
reader = new BufferedReader(new InputStreamReader(in));
System.out.print("step3"+reader);
String line;
while ((line = reader.readLine()) != null) {
sb.append(line);
sb.append("\n");
}
System.out.print("step4"+sb);
reader.close();
result = sb.toString();
System.out.print("step5"+result);
} catch (MalformedURLException e) {
e.printStackTrace();
System.out.print("Hiiiiiiiiiiiiiiiiiiii"+e.getMessage());
} catch (IOException e) {
e.printStackTrace();
System.out.print("Byeeeeeeeeee"+e.getMessage());
} finally {
if (null!=reader) {
try {
reader.close();
} catch (IOException e) {
e.printStackTrace();
System.out.print("Hellllloooooooo"+e.getMessage());
}
}
}
return result;
}
Find the solution Post and Get using HttpUrlConnection
private Object doSendRequest(final int requestCode, String url, final Object params, final String sessionId, final String requestType, final Activity parentActivity) {
URL myurl;
Log.v("sessionId", sessionId + "");
HttpsURLConnection httpsURLConnection = null;
try {
if (requestType.equalsIgnoreCase("GET")) {
if (params.toString().length() >= 1) {
if (url.contains("?")) {
url = (url + params.toString());
} else {
url = (url + "?" + params.toString());
}
}
}
myurl = new URL(url);
Log.v("RequestCode, URL", requestCode + " : " + url);
httpsURLConnection = (HttpsURLConnection) myurl.openConnection();
httpsURLConnection.setRequestMethod(requestType);
httpsURLConnection.setUseCaches(true);
if (isOnline(parentActivity)) {
httpsURLConnection.addRequestProperty("Cache-Control", "max-age=0");
} else {
httpsURLConnection.setUseCaches(true);
httpsURLConnection.addRequestProperty("Cache-Control", "max-stale=" + CACHE_STALE_TIME_OUT);
httpsURLConnection.addRequestProperty("Cache-Control", "only-if-cached");
}
httpsURLConnection.setConnectTimeout(20 * ONE_SECOND);
httpsURLConnection.setReadTimeout(20 * ONE_SECOND);
httpsURLConnection.setInstanceFollowRedirects(true);
httpsURLConnection.setRequestProperty("Content-Type", CONTENT_TYPE_APPLICATION_JSON);
if (sessionId != null) {
httpsURLConnection.setRequestProperty("sessionId", sessionId);
}
httpsURLConnection.setDoInput(true);
if (!requestType.equalsIgnoreCase("GET")) {
Log.v("RequestData", "" + params.toString());
httpsURLConnection.setDoOutput(true);
BufferedWriter writer = null;
try {
writer = new BufferedWriter(new OutputStreamWriter(httpsURLConnection.getOutputStream(), "UTF-8"));
writer.write(params.toString());
writer.flush();
}catch (Exception e){
e.printStackTrace();
}finally {
if(writer != null){
try {
writer.close();
}catch (Exception e){
e.printStackTrace();
}
}
}
}
httpsURLConnection.connect();
} catch (Exception e) {
Log.v("Ex", "1");
e.printStackTrace();
handleException(requestCode, e, parentActivity);
return null;
}
//---------------------READING THE RESPONSE---------------------------//
BufferedReader bReader = null;
try {
final String newSessionId = httpsURLConnection.getHeaderField("sessionId");
final int httpResponseCode = httpsURLConnection.getResponseCode();
Log.v("Req, Response codes", requestCode+", "+httpResponseCode);
if(httpResponseCode == 504 && !LegionUtils.isOnline(parentActivity)){
parentActivity.runOnUiThread(new Runnable() {
#Override
public void run() {
hideProgressDialog();
showOfflineDialog(parentActivity);
}
});
return null;
}
if (httpResponseCode == 401) {
parentActivity.runOnUiThread(new Runnable() {
#Override
public void run() {
hideProgressDialog();
}
});
return null;
} else if ((httpResponseCode == 400 || (httpResponseCode >= 500 && httpResponseCode <= 599)) && !(parentActivity instanceof CreateAccountActivity)) {
parentActivity.runOnUiThread(new Runnable() {
#Override
public void run() {
hideProgressDialog();
networkCallback.onFailure(requestCode, null);
}
});
return null;
} else if ((httpResponseCode >= 500 && httpResponseCode <= 599) && (parentActivity instanceof CreateAccountActivity)) {
parentActivity.runOnUiThread(new Runnable() {
#Override
public void run() {
networkCallback.onFailure(requestCode, null);
}
});
return null;
}
InputStream inputStream;
try {
inputStream = httpsURLConnection.getInputStream();
}catch (FileNotFoundException e){
e.printStackTrace();
inputStream = httpsURLConnection.getErrorStream();
}
if (inputStream != null) {
bReader = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"));
String inputLine;
final StringBuffer response = new StringBuffer();
while ((inputLine = bReader.readLine()) != null) {
response.append(inputLine);
}
bReader.close();
parentActivity.runOnUiThread(new Runnable() {
#Override
public void run() {
Log.v("RESPONSE " + requestCode, response.toString());
networkCallback.onSuccess(requestCode, response.toString(), newSessionId);
}
});
}
} catch (Exception e) {
Log.v("Ex", "2");
e.printStackTrace();
handleException(requestCode, e, parentActivity);
} finally {
try {
if (bReader != null) {
bReader.close();
}
} catch (Exception e) {
e.printStackTrace();
}
}
return null;
}
private void handleException(final int requestCode, Exception error, final Activity parentActivity) {
final String errorResponse;
if (error instanceof TimeoutException || error instanceof SocketTimeoutException || error instanceof UnknownHostException) {
errorResponse = "Your request has been timed out. Please try again later.";
} else if (error instanceof SSLException || error instanceof ConnectException) {
errorResponse = null;
parentActivity.runOnUiThread(new Runnable() {
#Override
public void run() {
hideProgressDialog();
showOfflineDialog(parentActivity);
}
});
} /*else if (error instanceof FileNotFoundException) {
errorResponse = "Invalid Request.\nPlease try again later.";
} */else if (error instanceof IOException) {
errorResponse = "Something went wrong. Please try again later.";
} else if (error instanceof JSONException) {
errorResponse = "Unexpected response.\nPlease try again later.";
} else {
errorResponse = null;
parentActivity.runOnUiThread(new Runnable() {
#Override
public void run() {
hideProgressDialog();
showOfflineDialog(parentActivity);
}
});
}
Log.v("FAILURE ERR RESPONSE " + requestCode, errorResponse + "");
parentActivity.runOnUiThread(new Runnable() {
#Override
public void run() {
networkCallback.onFailure(requestCode, errorResponse);
}
});
}
In my app, when you click on the button then I am downloading the images from the url's. It displaying the images some time correctly but some time it display empty. *problem is some times bitmap object(i.e, "result" in code ) return null.*please can anybody help me.
Following is my code
try
{
String ImageUrl = ((eachReview)RB_Constant.revht.get(title_value)).UserImageUrl;
System.out.println("Image Url:"+ImageUrl);
if(ImageUrl != null)
{
DownLoadImageInAThreadHandler(ImageUrl,holder);
}
else
{
System.out.println("Image url is null then display the default image");
holder.userImage.setImageResource(R.drawable.defaultuserimage);
}
}
catch(Exception e){
System.out.println("Error from Userimage fetching.."+e.toString());
}
private void DownLoadImageInAThreadHandler(final String imgurl,final ViewHolder holder)
{
//Thread for getting the attributes values
Thread t = new Thread()
{
public void run()
{
try
{
Bitmap drawable = getDrawableFromUrl(imgurl);
System.out.println("Drawable(after downloading):"+drawable);
if(drawable != null)
{
holder.userImage.setImageBitmap(drawable);
}
else
{
System.out.println("after downloading drawable is null then set the default image");
holder.userImage.setImageResource(R.drawable.defaultuserimage);
}
}
catch(Exception exp)
{
System.out.println("Exception in DownLoadImageInAThread : " + exp.getMessage());
}
}
private Bitmap getDrawableFromUrl(String imageUrl)
{
try
{
URL myFileUrl = new URL(imageUrl);
HttpURLConnection conn = (HttpURLConnection) myFileUrl.openConnection();
conn.setDoInput(true);
conn.connect();
InputStream is = conn.getInputStream();
final Bitmap result = BitmapFactory.decodeStream(is);
is.close();
new Thread() {
public void run() {
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
if(result != null)
{
result.compress(Bitmap.CompressFormat.JPEG, 40, bytes);
}
}
}.start();
return result;
}
catch (FileNotFoundException e)
{
e.printStackTrace();
}
catch (MalformedURLException e)
{
e.printStackTrace();
}
catch (IOException e)
{
e.printStackTrace();
}
return null;
}
};
t.start();
}
Try making you getDrawableFromUrl as:
public static Drawable getDrawableFromUrl(String url) {
Drawable image = null;
try {
InputStream in = (java.io.InputStream) new java.net.URL(url).getContent();
if (in != null) {
image = Drawable.createFromStream(in, "image");
in.close();
}
} catch (Exception ex) {
ex.printStackTrace();
}
return image;
}
Also do not compress image within same function. Try Doing it after you successfully receive an image. One thing more that write getDrawableFromUrl function out of the thread but in same class. Hope this works for you.