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;
Related
public class GetPlaceSearchTask extends AsyncTask<String , Void ,String>
{
private Context context;
private ProgressDialog dialog;
public static final String SEND_RESULT_SEARCH_BROADCAST_FROM_TASK = "send_result_search";
private String API_LOCATION = "https://maps.googleapis.com/maps/api/place/nearbysearch/" +
"json?location=-33.8670522,151.1957362&radius=500&type=restaurant&name=cruise&key=";
public GetPlaceSearchTask(Context context) {
this.context = context;
}
protected void onPreExecute() {
if (context != null) {
dialog = new ProgressDialog(context);
dialog.setTitle("Downloading");
dialog.show();
}
}
#Override
protected String doInBackground(String... params) {
HttpsURLConnection connection = null;
BufferedReader reader = null;
StringBuilder builder = new StringBuilder();
try {
URL url = new URL(String.format(API_LOCATION, params[0], params[1]));
connection = (HttpsURLConnection) url.openConnection();
if (connection.getResponseCode() != HttpsURLConnection.HTTP_OK) {
return null;
}
reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
String line;
while ((line = reader.readLine()) != null) {
builder.append(line);
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
if (connection != null) {
connection.disconnect();
}
if (reader != null) {
try {
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return builder.toString();
}
#Override
protected void onPostExecute(String result) {
if (dialog != null) {
dialog.dismiss();
}
Intent intent = new Intent(SEND_RESULT_SEARCH_BROADCAST_FROM_TASK);
intent.putExtra("result_search", result);
LocalBroadcastManager.getInstance(context).sendBroadcast(intent);
}
public static class GetPlaceSearchTextTask extends AsyncTask<String , Void , String>{
private String API_TEXT = "https://maps.googleapis.com/maps/api/place/textsearch/" +
"json?query=%1$s&location=[%2$s,%3$s]&radius=5000&key=";
public static final String SEND_BROADCAST_RESULT_TEXT_FROM_TASK = "sand_text_result";
private Context context;
private ProgressDialog dialog ;
public GetPlaceSearchTextTask(Context context){
this.context = context;
}
#Override
protected void onPreExecute() {
if (context != null) {
dialog = new ProgressDialog(context);
dialog.setTitle("Downloading");
dialog.show();
}
}
#Override
protected String doInBackground(String... params) {
HttpsURLConnection connection = null;
BufferedReader reader = null;
StringBuilder builder = new StringBuilder() ;
try {
URL url = new URL(API_TEXT + params[0] + params[1] + params[2]) ;
connection = (HttpsURLConnection) url.openConnection();
if (connection.getResponseCode() != HttpsURLConnection.HTTP_OK){
return null;
}
reader = new BufferedReader(new InputStreamReader(connection.getInputStream())) ;
String line;
while ((line=reader.readLine())!= null){
builder.append(line);
}`enter code here`
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
if (connection!=null)
connection.disconnect();
if (reader!=null)
try {
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
return builder.toString();
}
#Override
protected void onPostExecute(String result_text) {
if (dialog!=null){
dialog.dismiss();
}`enter code here`
Intent intent = new Intent(SEND_BROADCAST_RESULT_TEXT_FROM_TASK);
intent.putExtra("text" , result_text);
LocalBroadcastManager.getInstance(context).sendBroadcast(intent);
}
}
}
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.
Code :
public class SocketOperator implements ISocketOperator
{
private static final String AUTHENTICATION_SERVER_ADDRESS = "http://192.168.1.8/android-im/index.php"; //TODO change to your WebAPI Address
private int listeningPort = 0;
private static final String HTTP_REQUEST_FAILED = "failed";
private HashMap<InetAddress, Socket> sockets = new HashMap<InetAddress, Socket>();
private ServerSocket serverSocket = null;
private boolean listening;
private IAppManager appManager;
private class ReceiveConnection extends Thread {
Socket clientSocket = null;
public ReceiveConnection(Socket socket)
{
this.clientSocket = socket;
SocketOperator.this.sockets.put(socket.getInetAddress(), socket);
}
#Override
public void run() {
try {
// PrintWriter out = new PrintWriter(clientSocket.getOutputStream(), true);
BufferedReader in = new BufferedReader(
new InputStreamReader(
clientSocket.getInputStream()));
String inputLine;
while ((inputLine = in.readLine()) != null)
{
if (inputLine.equals("exit") == false)
{
//appManager.messageReceived(inputLine);
}
else
{
clientSocket.shutdownInput();
clientSocket.shutdownOutput();
clientSocket.close();
SocketOperator.this.sockets.remove(clientSocket.getInetAddress());
}
}
} catch (IOException e) {
Log.e("ReceiveConnection.run: when receiving connection ","");
}
}
}
public SocketOperator(IAppManager appManager) {
this.appManager = appManager;
}
public String sendHttpRequest(String params)
{
URL url;
String result = new String();
try
{
url = new URL(AUTHENTICATION_SERVER_ADDRESS);
HttpURLConnection connection;
connection = (HttpURLConnection) url.openConnection();
connection.setDoOutput(true);
PrintWriter out = new PrintWriter(connection.getOutputStream());
out.println(params);
out.close();
BufferedReader in = new BufferedReader(
new InputStreamReader(
connection.getInputStream()));
String inputLine;
while ((inputLine = in.readLine()) != null) {
result = result.concat(inputLine);
}
in.close();
}
catch (MalformedURLException e) {
e.printStackTrace();
}
catch (IOException e) {
e.printStackTrace();
}
if (result.length() == 0) {
result = HTTP_REQUEST_FAILED;
}
return result;
}
public int startListening(int portNo)
{
listening = true;
try {
serverSocket = new ServerSocket(portNo);
this.listeningPort = portNo;
} catch (IOException e) {
//e.printStackTrace();
this.listeningPort = 0;
return 0;
}
while (listening) {
try {
new ReceiveConnection(serverSocket.accept()).start();
} catch (IOException e) {
//e.printStackTrace();
return 2;
}
}
try {
serverSocket.close();
} catch (IOException e) {
Log.e("Exception server socket", "Exception when closing server socket");
return 3;
}
return 1;
}
public void stopListening()
{
this.listening = false;
}
private Socket getSocket(InetAddress addr, int portNo)
{
Socket socket = null;
if (sockets.containsKey(addr) == true)
{
socket = sockets.get(addr);
// check the status of the socket
if ( socket.isConnected() == false ||
socket.isInputShutdown() == true ||
socket.isOutputShutdown() == true ||
socket.getPort() != portNo
)
{
// if socket is not suitable, then create a new socket
sockets.remove(addr);
try {
socket.shutdownInput();
socket.shutdownOutput();
socket.close();
socket = new Socket(addr, portNo);
sockets.put(addr, socket);
}
catch (IOException e) {
Log.e("getSocket: when closing and removing", "");
}
}
}
else
{
try {
socket = new Socket(addr, portNo);
sockets.put(addr, socket);
} catch (IOException e) {
Log.e("getSocket: when creating", "");
}
}
return socket;
}
public void exit()
{
for (Iterator<Socket> iterator = sockets.values().iterator(); iterator.hasNext();)
{
Socket socket = (Socket) iterator.next();
try {
socket.shutdownInput();
socket.shutdownOutput();
socket.close();
} catch (IOException e)
{
}
}
sockets.clear();
this.stopListening();
appManager = null;
// timer.cancel();
}
public int getListeningPort() {
return this.listeningPort;
}
}
I'm trying to export and import the SharedPreferences file from my device i asked here the question before and i saw a example code of someone but i have problem with the"Entry" :
it given me:
The type DropBoxManager.Entry is not generic; it cannot be
parameterized with arguments <String, ?>
private boolean saveSharedPreferencesToFile(File dst) {
boolean res = false;
ObjectOutputStream output = null;
try {
output = new ObjectOutputStream(new FileOutputStream(dst));
SharedPreferences pref = context.getSharedPreferences(MySharedPreferences.MY_TEMP, 1);
output.writeObject(pref.getAll());
res = true;
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}finally {
try {
if (output != null) {
output.flush();
output.close();
}
} catch (IOException ex) {
ex.printStackTrace();
}
}
return res;
}
#SuppressWarnings({ "unchecked" })
private boolean loadSharedPreferencesFromFile(File src) {
boolean res = false;
ObjectInputStream input = null;
try {
input = new ObjectInputStream(new FileInputStream(src));
Editor prefEdit = context.getSharedPreferences(MySharedPreferences.MY_TEMP, 1).edit();
prefEdit.clear();
Map<String, ?> entries = (Map<String, ?>) input.readObject();
for (Entry<String, ?> entry : entries.entrySet()) {
Object v = entry.getValue();
String key = entry.getKey();
if (v instanceof Boolean)
prefEdit.putBoolean(key, ((Boolean) v).booleanValue());
else if (v instanceof Float)
prefEdit.putFloat(key, ((Float) v).floatValue());
else if (v instanceof Integer)
prefEdit.putInt(key, ((Integer) v).intValue());
else if (v instanceof Long)
prefEdit.putLong(key, ((Long) v).longValue());
else if (v instanceof String)
prefEdit.putString(key, ((String) v));
}
prefEdit.commit();
res = true;
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}finally {
try {
if (input != null) {
input.close();
}
} catch (IOException ex) {
ex.printStackTrace();
}
}
return res;
}
Wrong Entry object.
You want Map.Entry<K, V>
http://docs.oracle.com/javase/7/docs/api/java/util/Map.Entry.html
My application requires root access. For example this code:
Process p;
try {
p = Runtime.getRuntime().exec("su");
BufferedReader es = new BufferedReader(new InputStreamReader(p.getErrorStream()));
String line;
if((line = es.readLine()) != null)
{
if(line.contentEquals("Permission denied"))
Log.e("TrisTag", "ROOT isn't granted");
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
So I know when my root access is denied (Read from the error stream). But what's about granted ? How to know ?
Answer from kevin.
public class Root {
private static String LOG_TAG = Root.class.getName();
public boolean isDeviceRooted() {
if (checkRootMethod1()){return true;}
if (checkRootMethod2()){return true;}
if (checkRootMethod3()){return true;}
return false;
}
public boolean checkRootMethod1(){
String buildTags = android.os.Build.TAGS;
if (buildTags != null && buildTags.contains("test-keys")) {
return true;
}
return false;
}
public boolean checkRootMethod2(){
try {
File file = new File("/system/app/Superuser.apk");
if (file.exists()) {
return true;
}
} catch (Exception e) { }
return false;
}
public boolean checkRootMethod3() {
if (new ExecShell().executeCommand(SHELL_CMD.check_su_binary) != null){
return true;
}else{
return false;
}
}
}
/**
* #author Kevin Kowalewski
*
*/
public class ExecShell {
private static String LOG_TAG = ExecShell.class.getName();
public static enum SHELL_CMD {
check_su_binary(new String[] {"/system/xbin/which","su"}),
;
String[] command;
SHELL_CMD(String[] command){
this.command = command;
}
}
public ArrayList<String> executeCommand(SHELL_CMD shellCmd){
String line = null;
ArrayList<String> fullResponse = new ArrayList<String>();
Process localProcess = null;
try {
localProcess = Runtime.getRuntime().exec(shellCmd.command);
} catch (Exception e) {
return null;
}
BufferedWriter out = new BufferedWriter(new OutputStreamWriter(localProcess.getOutputStream()));
BufferedReader in = new BufferedReader(new InputStreamReader(localProcess.getInputStream()));
try {
while ((line = in.readLine()) != null) {
Log.d(LOG_TAG, "--> Line received: " + line);
fullResponse.add(line);
}
} catch (Exception e) {
e.printStackTrace();
}
Log.d(LOG_TAG, "--> Full response was: " + fullResponse);
return fullResponse;
}