How to check timeout when load data from sever with Gson - android

new JSONData().execute(LinkData.HOME,LinkData.HOT,LinkData.NEW,LinkData.LIST_CATEGORY);
private class JSONData extends AsyncTask<String, Void, JSONArrayData> {
#Override
protected void onPreExecute() {
loading = true;
super.onPreExecute();
}
#Override
protected JSONArrayData doInBackground(String... params) {
CanBackPress = false;
URL url;
try {
for (int i = 0; i < params.length; i++) {
if (checkInternet.checkMobileInternetConn()) {
url = new URL(params[i]);
InputStreamReader reader = new InputStreamReader(url.openStream(), "UTF-8");
if (i == 0) {
Post[] post;
post = new Gson().fromJson(reader, Post[].class);
for (Post p : post) {
data.getData().get(0).add(p);
// Log.d("post", "" + post.length);
Methods.savePostData(getBaseContext(), arrName[0], p);
}
}
if (i == 1) {
Post[] post;
post = new Gson().fromJson(reader, Post[].class);
for (Post p : post) {
data.getData().get(1).add(p);
Methods.savePostData(getBaseContext(), arrName[3], p);
Methods.savePostData(getBaseContext(), arrName[1], p);
}
}
if (i == 2) {
Post[] post;
post = new Gson().fromJson(reader, Post[].class);
for (Post p : post) {
data.getData().get(2).add(p);
Methods.savePostData(getBaseContext(), arrName[2], p);
}
}
if (i == 3) {
Zone[] zone;
zone = new Gson().fromJson(reader, Zone[].class);
for (Zone z : zone) {
data.getZoneList().get(0).add(z);
listCategory.add(z);
}
}
} else {
break;
}
}
} catch (IOException e) {
e.printStackTrace();
}
return data;
}
#Override
protected void onPostExecute(JSONArrayData d) {
super.onPostExecute(d);
CanBackPress = true;
stopThread = true;
intent.putExtra("MyData", d);
// if (d.getData().get(0).size() == 0 || d.getData().get(1).size() == 0 || d.getZoneList().get(0).size() == 0) {
// Log.d("LOI","LOI");
// showDialog();
// } else {
// neu tu push
if (toNotify) {
Log.d("eu tu push", "eu tu push");
startActivity(intent);
finish();
} else {
loading = false;
loadfn = true;
if (clickFalse == 0 && clickTrue == 0) {
Log.d("boqua","boqua");
//checkbox2();
stopThread = true;
startActivity(intent);
finish();
} else if (login) {
Log.d("facebook","facebook");
stopThread = true;
startActivity(intent);
finish();
}
}
}
}
I loaded data Json from sever with Gson. Now I want check for errors with the following cases:
- timeout (most important)
- if Json null or Non-standard
How I to do it?
My code load data
and I call it with :

As you can see from this answer, the Exception thrown for time out is java.net.SocketTimeoutException

Related

how to integrate google assistant in android for native application?

I have gone through many tutorials with API.AI But didn't get the exact solution. My requirement is simply:- user will send some command using voice or text and get that commands in my application and execute some method.
API.AI
Actions on Google
Tutorial of Google Assistant
First of all you need to train your model on API.AI to respond upon some text given to the model.
Some code with API.AI FYI:
//Initialize Service
private void initService(final LanguageConfig selectedLanguage) {
try {
final AIConfiguration.SupportedLanguages lang = AIConfiguration.SupportedLanguages.fromLanguageTag(selectedLanguage.getLanguageCode());
final AIConfiguration config = new AIConfiguration(selectedLanguage.getAccessToken(),
lang,
AIConfiguration.RecognitionEngine.System);
aiDataService = new AIDataService(this, config);
} catch (Exception e) {
e.printStackTrace();
}
}
//Send request method where you can put user typed text to get the result from API.AI
private void sendRequest(final String textToSend, final int flag) {
Log.w(TAG, "Sending" + textToSend);
final AsyncTask<String, Void, AIResponse> task = new AsyncTask<String, Void, AIResponse>() {
private AIError aiError;
#Override
protected void onPreExecute() {
super.onPreExecute();
showHideProgressBar(true);
if (mVoiceRecorder != null) {
mVoiceRecorder.pauseRecording();
}
}
#Override
protected AIResponse doInBackground(final String... params) {
final AIRequest request = new AIRequest();
String query = params[0];
String event = params[1];
if (!TextUtils.isEmpty(query))
request.setQuery(query);
if (!TextUtils.isEmpty(event)) {
request.setEvent(new AIEvent(event));
}
final String contextString = params[2];
RequestExtras requestExtras = null;
if (!TextUtils.isEmpty(contextString)) {
final List<AIContext> contexts = Collections.singletonList(new AIContext(contextString));
requestExtras = new RequestExtras(contexts, null);
}
try {
Log.i("API AI Request", "" + request.toString());
return aiDataService.request(request, requestExtras);
} catch (final AIServiceException e) {
aiError = new AIError(e);
return null;
}
}
#Override
protected void onPostExecute(final AIResponse response) {
showHideProgressBar(false);
speechSentStatus = false;
okSentStatus = false;
if (response != null) {
onResult(response, flag, textToSend);
} else {
onError(aiError);
}
}
};
if (flag == OPEN_COMPLAIN_CODE) {
task.execute("", Config.Events[0], Config.Events[0]);
} else if (flag == OPEN_DIAGNOSIS_CODE) {
task.execute("", Config.Events[1], Config.Events[1]);
} else if (flag == Constants.OPEN_MEDICATION_CODE) {
task.execute("", Config.Events[2], Config.Events[2]);
} else if (flag == Constants.OPEN_LABTEST_CODE) {
task.execute("", Config.Events[3], Config.Events[3]);
} else if (flag == Constants.COMPLAINTS_ADDED) {
task.execute("", Config.Events[0], Config.Events[0]);
} else if (flag == Constants.DIAGNOSIS_ADDED) {
task.execute("", Config.Events[1], Config.Events[1]);
} else {
task.execute(textToSend, null, "");
}
}
//Based on result you can handle the business logic
private void onResult(final AIResponse response, final int flag, final String textToSend) {
runOnUiThread(new Runnable() {
#Override
public void run() {
apiAiResponseCounter = apiAiResponseCounter + 1;
isLast = false;
final Result result = response.getResult();
Log.w(TAG, "" + result.getFulfillment().getSpeech());
if (flag == Constants.COMPLAINTS_ADDED) {
//method you want to execute on receiving certain text from model
send(textToSend.toLowerCase(), DONTTEXT);
} else if (flag == Constants.DIAGNOSIS_ADDED) {
send(textToSend.toLowerCase(), DONTTEXT);
} else {
String error = "";
final String speech = result.getFulfillment().getSpeech();
if (speech.contains("?")) {
if (!result.getAction().equalsIgnoreCase("input.unknown")) {
if (result.getAction().equalsIgnoreCase(Config.Actions[5]) && result.isActionIncomplete() == false) {
//DONOTHING
} else {
digiMessage(speech, YESNO);
}
} else {
digiMessage(speech, ChatMessageAdapter.OTHER_MESSAGE);
}
} else {
if (speech.equalsIgnoreCase("Please help me the intake duration of the medication")) {
digiMessage(speech, ChatMessageAdapter.DURATION);
} else if (speech.equalsIgnoreCase("Please provide the daily routine for the medication intake")) {
digiMessage(speech, ChatMessageAdapter.FREQUENCY);
} else {
digiMessage(speech, ChatMessageAdapter.OTHER_MESSAGE);
}
}
if (result.getAction().equalsIgnoreCase(Config.Actions[4]) || result.getAction().equalsIgnoreCase(Config.Actions[5])) {
if (result.isActionIncomplete() == true) {
playSpeech(speech);
} else {
speechBuffer = "";
speechBuffer = speech;
}
} else {
if (result.getAction().equalsIgnoreCase(Config.Actions[11])) {
isLast = true;
if (mVoiceRecorder != null) {
stopVoiceRecording();
}
} else {
playSpeech(speech);
}
}
}
}
});
if (flag == Constants.COMPLAINTS_ADDED || flag == Constants.DIAGNOSIS_ADDED) {
Log.w(TAG, "Skipped");
} else {
inflateUI(response.getResult());
}
}

AppsFlyer Android onInstallConversionDataLoaded delay callback

Ok so i grabbed the code from AppsFlyer Cordova plugin:
AppsFlyerProperties.getInstance().set(AppsFlyerProperties.LAUNCH_PROTECT_ENABLED, false);
AppsFlyerLib instance = AppsFlyerLib.getInstance();
try{
final JSONObject options = args.getJSONObject(0);
devKey = options.optString(AF_DEV_KEY, "");
isConversionData = options.optBoolean(AF_CONVERSION_DATA, false);
if(devKey.trim().equals("")){
callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.ERROR, NO_DEVKEY_FOUND));
}
isDebug = options.optBoolean(AF_IS_DEBUG, false);
instance.setDebugLog(isDebug);
if(isDebug == true){
System.out.println("AppsFlyer Here 0");
Log.d("AppsFlyer", "Starting Tracking");
}
trackAppLaunch();
instance.startTracking(c.getApplication(), devKey);
if(isConversionData == true){
if(mAttributionDataListener == null) {
mAttributionDataListener = callbackContext;
}
if(mConversionListener == null){
mConversionListener = callbackContext;
}
registerConversionListener(instance);
sendPluginNoResult(callbackContext);
}
else{
callbackContext.success(SUCCESS);
}
}
catch (JSONException e){
e.printStackTrace();
}
registerConversionListener
private void registerConversionListener(AppsFlyerLib instance){
instance.registerConversionListener(cordova.getActivity().getApplicationContext(), new AppsFlyerConversionListener(){
#Override
public void onAppOpenAttribution(Map<String, String> attributionData) {
}
#Override
public void onAttributionFailure(String errorMessage) {
handleError(AF_ON_ATTRIBUTION_FAILURE, errorMessage);
}
#Override
public void onInstallConversionDataLoaded(Map<String, String> conversionData) {
// Delay here up to some minutes
}
OnInstallCoversionDataLoaded callback is delayed up to some minutes. Can anyone advise how to fix this?

Why my json data not following an order in API 16 and lower API?

Explanation:I have json.In which, i have object namely matches.Inside the matches object i have lot of objects.I mean data->season->matches->object1,2,3 so on.
This objects are dynamic it's not fixed at the run-time.I tried to parse the matches object.
Here is my json data
Now i tried to parse this file using my url.I was used a volley network library to parse the json file from server.
Here is my code to parse the json and get the response
public class SeriesActivity extends AppCompatActivity {
Toolbar toolbar;
String series_key = "";
String url = "";
String access_token = "";
FrameLayout frameLayout;
List<SeriesMatches> series_header;
HashMap<SeriesMatches, List<SeriesMatches>> series_child;
String winner_team = "";
String overs = "";
String wickets_now = "";
String now_runs = "";
String now_bat_team = "";
String fullScore = "";
String team_name = "";
String[] over_parts;
ExpandableListView expListView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_series);
toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
if (getSupportActionBar() != null) {
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
}
frameLayout = (FrameLayout) findViewById(R.id.adbar);
new AddLoader(getApplicationContext()).LoadAds(frameLayout);
SharedPreferences sharedPreferences = this.getSharedPreferences("SaveTime", MODE_PRIVATE);
access_token = sharedPreferences.getString("accessToken", null);
expListView = (ExpandableListView) findViewById(R.id.lvExp);
Intent intent = getIntent();
series_key = intent.getStringExtra("series_key");
url = "https://api.litzscore.com/rest/v2/season/" + series_key + "/?access_token=" + access_token + "&card_type=summary_card";
if (!Utils.isNetworkConnected(this)) {
dialog_popup();
} else {
getSeriesMatches();
}
}
public void getSeriesMatches() {
String str_req = "getSeries";
StringRequest matches_req = new StringRequest(Request.Method.GET, url, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
if (response != null) {
try {
JSONObject object = new JSONObject(response);
if (!object.getBoolean("status") || object.getString("status_code").equals("403")) {
// DialogAbandoned abandoned=new DialogAbandoned(getApplicationContext());
// abandoned.setDialog("Series","Data Coming soon...");
} else {
series_header = new ArrayList<>();
series_child = new HashMap<>();
if (object.has("data") && !object.isNull("data")) {
JSONObject data = object.getJSONObject("data");
JSONObject season;
JSONObject matches;
if (data.has("season") && !data.isNull("season")) {
season = data.getJSONObject("season");
if (season.has("matches") && !season.isNull("matches")) {
matches = season.getJSONObject("matches");
JSONArray matches_arr = matches.names();
JSONObject matches_obj;
for (int i = 0; i < matches_arr.length(); i++) {
SeriesMatches s_matches = new SeriesMatches();
matches_obj = matches.getJSONObject(matches_arr.getString(i));
JSONObject teams = matches_obj.getJSONObject("teams");
JSONObject team_a = teams.getJSONObject("a");
JSONObject team_b = teams.getJSONObject("b");
JSONObject start_date = matches_obj.getJSONObject("start_date");
s_matches.setRealted_name(matches_obj.getString("related_name"));
series_header.add(s_matches);
if (!matches_obj.isNull("msgs") && matches_obj.has("msgs")) {
JSONObject msgs = matches_obj.getJSONObject("msgs");
winner_team = "";
if (msgs.has("info")) {
winner_team = msgs.getString("info");
}
}
JSONObject now;
now_bat_team = "";
now_runs = "";
wickets_now = "";
overs = "";
if (matches_obj.has("now") && !matches_obj.isNull("now")) {
now = matches_obj.getJSONObject("now");
if (now.has("batting_team")) {
now_bat_team = now.getString("batting_team");
}
if (now.has("runs")) {
if (now.getString("runs").equals("0")) {
now_runs = "0";
} else {
now_runs = now.getString("runs");
}
}
if (now.has("runs_str") && !now.isNull("runs_str")) {
if (now.getString("runs_str").equals("0")) {
overs = "0";
} else {
if (now.getString("runs_str").equals("null")) {
overs = "0";
} else {
over_parts = now.getString("runs_str").split(" ");
overs = over_parts[2];
}
}
}
if (now.has("wicket")) {
if (now.getString("wicket").equals("0")) {
wickets_now = "0";
} else {
wickets_now = now.getString("wicket");
}
}
}
JSONArray team_arr = teams.names();
JSONObject team_obj;
for (int a = 0; a < team_arr.length(); a++) {
if (now_bat_team.equals(team_arr.getString(a))) {
team_obj = teams.getJSONObject(team_arr.getString(a));
team_name = "";
if (team_obj.has("short_name") && !team_obj.isNull("short_name")) {
team_name = team_obj.getString("short_name");
}
}
}
if (matches_obj.has("status_overview") && !matches_obj.isNull("status_overview")) {
if (matches_obj.getString("status_overview").equals("abandoned") || matches_obj.getString("status_overview").equals("canceled")) {
fullScore = "";
} else {
fullScore = team_name + " - " + now_runs + "/" + wickets_now + " (" + overs + " ovr)";
}
}
SeriesMatches s2 = new SeriesMatches();
s2.setTeam_Aname(team_a.getString("short_name"));
s2.setTemm_Akey(team_a.getString("key"));
s2.setTeam_Bname(team_b.getString("short_name"));
s2.setTeam_Bkey(team_b.getString("key"));
s2.setStatus(matches_obj.getString("status"));
s2.setDate(start_date.getString("iso"));
s2.setVenue(matches_obj.getString("venue"));
s2.setMsgs(winner_team);
s2.setScore(fullScore);
s2.setMom(matches_obj.getString("man_of_match"));
List<SeriesMatches> matches_info = new ArrayList<>();
matches_info.add(s2);
series_child.put(series_header.get(i), matches_info);
}
}
}
}
}
} catch (JSONException e) {
e.printStackTrace();
}
}
ExpandedListAdapter adapter = new ExpandedListAdapter(getApplicationContext(), series_header, series_child);
expListView.setAdapter(adapter);
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
if (error instanceof TimeoutError || error instanceof NoConnectionError) {
dialog_popup();
} else if (error instanceof AuthFailureError) {
dialog_popup();
} else if (error instanceof ServerError) {
dialog_popup();
} else if (error instanceof NetworkError) {
dialog_popup();
} else if (error instanceof ParseError) {
dialog_popup();
}
}
});
AppController.getInstance().addToRequestQueue(matches_req, str_req);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
finish();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
}
Here is my Expnadedlistview
public class ExpandedListAdapter extends BaseExpandableListAdapter{
private Context context;
private List<SeriesMatches> series_header;
private HashMap<SeriesMatches,List<SeriesMatches>> series_child;
private Typeface tf;
public ExpandedListAdapter(Context context,List<SeriesMatches> series_header,HashMap<SeriesMatches,List<SeriesMatches>> series_child){
this.context=context;
this.series_header=series_header;
this.series_child=series_child;
}
#Override
public int getGroupCount() {
return this.series_header.size();
}
#Override
public int getChildrenCount(int groupPosition) {
return this.series_child.get(this.series_header.get(groupPosition)).size();
}
#Override
public Object getGroup(int groupPosition) {
return this.series_header.get(groupPosition);
}
#Override
public Object getChild(int groupPosition, int childPosition) {
return this.series_child.get(this.series_header.get(groupPosition)).get(childPosition);
}
#Override
public long getGroupId(int groupPosition) {
return groupPosition;
}
#Override
public long getChildId(int groupPosition, int childPosition) {
return childPosition;
}
#Override
public boolean hasStableIds() {
return false;
}
#Override
public View getGroupView(int groupPosition, boolean isExpanded, View convertView, ViewGroup parent) {
if(convertView==null){
LayoutInflater inflater=(LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView=inflater.inflate(R.layout.list_group,null);
}
TextView text_group=(TextView)convertView.findViewById(R.id.lblListHeader);
SeriesMatches s=series_header.get(groupPosition);
text_group.setText(s.getRealted_name());
return convertView;
}
#Override
public View getChildView(int groupPosition, int childPosition, boolean isLastChild, View convertView, ViewGroup parent) {
if(convertView==null){
LayoutInflater inflater=(LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView=inflater.inflate(R.layout.list_child,null);
tf = Typeface.createFromAsset(convertView.getResources().getAssets(), "Roboto-Regular.ttf");
}
TextView teamA=(TextView)convertView.findViewById(R.id.txt_one_country_name);
TextView teamB=(TextView)convertView.findViewById(R.id.txt_two_country_name);
TextView txt_venue=(TextView)convertView.findViewById(R.id.venue);
TextView txtTimeIST=(TextView)convertView.findViewById(R.id.txt_timeist);
TextView txtTimeGMT=(TextView)convertView.findViewById(R.id.txt_timegmt);
TextView txtDate=(TextView)convertView.findViewById(R.id.txt_date);
ImageView team_one_flag_icon=(ImageView)convertView.findViewById(R.id.team_one_flag_icon);
ImageView team_two_flag_icon=(ImageView)convertView.findViewById(R.id.team_two_flag_icon);
SeriesMatches s1=series_child.get(series_header.get(groupPosition)).get(childPosition);
String team_a_key=s1.getTemm_Akey();
String team_b_key=s1.getTeam_Bkey();
teamA.setText(s1.getTeam_Aname());
teamB.setText(s1.getTeam_Bname());
if(team_a_key.equals("ind")) {
team_one_flag_icon.setImageResource(R.drawable.ind);
}
else if(team_a_key.equals("omn")){
team_one_flag_icon.setImageResource(R.drawable.omn);
}
else if(team_a_key.equals("afg")) {
team_one_flag_icon.setImageResource(R.drawable.afg);
} else if(team_a_key.equals("aus")) {
team_one_flag_icon.setImageResource(R.drawable.aus);
} else if(team_a_key.equals("ban")) {
team_one_flag_icon.setImageResource(R.drawable.ban);
} else if(team_a_key.equals("eng")) {
team_one_flag_icon.setImageResource(R.drawable.eng);
} else if(team_a_key.equals("hkg")) {
team_one_flag_icon.setImageResource(R.drawable.hkg);
} else if(team_a_key.equals("ire")) {
team_one_flag_icon.setImageResource(R.drawable.ire);
} else if(team_a_key.equals("nl")) {
team_one_flag_icon.setImageResource(R.drawable.nl);
} else if(team_a_key.equals("nz")) {
team_one_flag_icon.setImageResource(R.drawable.nz);
} else if(team_a_key.equals("pak")) {
team_one_flag_icon.setImageResource(R.drawable.pak);
} else if(team_a_key.equals("rsa")) {
team_one_flag_icon.setImageResource(R.drawable.rsa);
}else if (team_a_key.equalsIgnoreCase("sl")) {
team_one_flag_icon.setImageResource(R.drawable.sl);
} else if (team_a_key.equals("uae")) {
team_one_flag_icon.setImageResource(R.drawable.uae);
} else if (team_a_key.equals("wi")) {
team_one_flag_icon.setImageResource(R.drawable.wi);
} else if (team_a_key.equals("zim")) {
team_one_flag_icon.setImageResource(R.drawable.zim);
} else if(team_a_key.equals("sct")) {
team_one_flag_icon.setImageResource(R.drawable.sct);
////////// IPL Team ///////////
} else if(team_a_key.equals("dd")) {
team_one_flag_icon.setImageResource(R.drawable.dd);
} else if(team_a_key.equals("kkr")) {
team_one_flag_icon.setImageResource(R.drawable.kkr);
} else if(team_a_key.equals("mi")) {
team_one_flag_icon.setImageResource(R.drawable.mi);
} else if(team_a_key.equals("srh")) {
team_one_flag_icon.setImageResource(R.drawable.sh);
} else if(team_a_key.equals("kxip")) {
team_one_flag_icon.setImageResource(R.drawable.kxip);
} else if(team_a_key.equals("rcb")) {
team_one_flag_icon.setImageResource(R.drawable.rcb);
} else if(team_a_key.equals("rps")) {
team_one_flag_icon.setImageResource(R.drawable.rps);
} else if(team_a_key.equals("gl")) {
team_one_flag_icon.setImageResource(R.drawable.gl);
} else {
team_one_flag_icon.setImageResource(R.drawable.dft);
}
//for B TEAM
if(team_b_key.equals("ind")) {
team_two_flag_icon.setImageResource(R.drawable.ind);
}
else if(team_b_key.equals("omn")){
team_two_flag_icon.setImageResource(R.drawable.omn);
}
else if(team_b_key.equals("afg")) {
team_two_flag_icon.setImageResource(R.drawable.afg);
} else if(team_b_key.equals("aus")) {
team_two_flag_icon.setImageResource(R.drawable.aus);
} else if(team_b_key.equals("ban")) {
team_two_flag_icon.setImageResource(R.drawable.ban);
} else if(team_b_key.equals("eng")) {
team_two_flag_icon.setImageResource(R.drawable.eng);
} else if(team_b_key.equals("hkg")) {
team_two_flag_icon.setImageResource(R.drawable.hkg);
} else if(team_b_key.equals("ire")) {
team_two_flag_icon.setImageResource(R.drawable.ire);
} else if(team_b_key.equals("nl")) {
team_two_flag_icon.setImageResource(R.drawable.nl);
} else if(team_b_key.equals("nz")) {
team_two_flag_icon.setImageResource(R.drawable.nz);
} else if(team_b_key.equals("pak")) {
team_two_flag_icon.setImageResource(R.drawable.pak);
} else if(team_b_key.equals("rsa")) {
team_two_flag_icon.setImageResource(R.drawable.rsa);
}else if (team_b_key.equalsIgnoreCase("sl")) {
team_two_flag_icon.setImageResource(R.drawable.sl);
} else if (team_b_key.equals("uae")) {
team_two_flag_icon.setImageResource(R.drawable.uae);
} else if (team_b_key.equals("wi")) {
team_two_flag_icon.setImageResource(R.drawable.wi);
} else if (team_b_key.equals("zim")) {
team_two_flag_icon.setImageResource(R.drawable.zim);
} else if(team_b_key.equals("sct")) {
team_two_flag_icon.setImageResource(R.drawable.sct);
////////// IPL ///////////
} else if(team_b_key.equals("dd")) {
team_two_flag_icon.setImageResource(R.drawable.dd);
} else if(team_b_key.equals("kkr")) {
team_two_flag_icon.setImageResource(R.drawable.kkr);
} else if(team_b_key.equals("mi")) {
team_two_flag_icon.setImageResource(R.drawable.mi);
} else if(team_b_key.equals("srh")) {
team_two_flag_icon.setImageResource(R.drawable.sh);
} else if(team_b_key.equals("kxip")) {
team_two_flag_icon.setImageResource(R.drawable.kxip);
} else if(team_b_key.equals("rcb")) {
team_two_flag_icon.setImageResource(R.drawable.rcb);
} else if(team_b_key.equals("rps")) {
team_two_flag_icon.setImageResource(R.drawable.rps);
} else if(team_b_key.equals("gl")) {
team_two_flag_icon.setImageResource(R.drawable.gl);
} else {
team_two_flag_icon.setImageResource(R.drawable.dft);
}
try {
String[] fullDate;
String fullTime = "";
DateFormat utcFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm'+00':ss");
utcFormat.setTimeZone(TimeZone.getTimeZone("UTC"));
DateFormat outputFormat = new SimpleDateFormat("hh:mm a");
String ist=outputFormat.format(utcFormat.parse(s1.getDate()));
Date timestamp;
timestamp = utcFormat.parse(s1.getDate());
fullDate = timestamp.toString().split(" ");
String monthName = fullDate[1];
String Dayname = fullDate[2];
fullTime = fullDate[3];
String[] gmt_fulldate = s1.getDate().split("T");
String gmt_time = gmt_fulldate[1];
String[] gmt_hour_parts = gmt_time.split("\\+");
String finalDate = Dayname + " " + monthName;
String finalTimeIST = ist + " IST | " + gmt_hour_parts[0] + " GMT";
String[] venue_parts=s1.getVenue().split(",");
int length=venue_parts.length;
if(length==1){
txtTimeGMT.setTextSize(TypedValue.COMPLEX_UNIT_SP, 13);
txtTimeGMT.setText(venue_parts[0]);
}
if(length==2){
txtTimeGMT.setTextSize(TypedValue.COMPLEX_UNIT_SP, 12);
txtTimeGMT.setText(venue_parts[0] + "," + venue_parts[1]);
}
if(length==3){
txtTimeGMT.setTextSize(TypedValue.COMPLEX_UNIT_SP,12);
txtTimeGMT.setText(venue_parts[1] + "," + venue_parts[2]);
}
if(length==4){
txtTimeGMT.setTextSize(TypedValue.COMPLEX_UNIT_SP,12);
txtTimeGMT.setText(venue_parts[2] + "," + venue_parts[3]);
}
if(s1.getStatus().equals("notstarted")){
txtDate.setTextSize(TypedValue.COMPLEX_UNIT_SP, 15);
txtDate.setTypeface(tf);
txtDate.setText("Started on " + finalDate);
txtTimeIST.setVisibility(View.VISIBLE);
txtTimeIST.setText(finalTimeIST);
}
if(s1.getStatus().equals("completed")){
txtDate.setTypeface(tf);
txtDate.setText(s1.getScore());
txtDate.setTextSize(TypedValue.COMPLEX_UNIT_SP, 14);
txtTimeIST.setVisibility(View.VISIBLE);
txtTimeIST.setText(s1.getMsgs());
Log.e("NOTSTARTED","DONE");
txt_venue.setText("MOM : "+s1.getMom().substring(0, 1).toUpperCase() + s1.getMom().substring(1).replace("_", " "));
}
}
catch (ParseException e){
e.printStackTrace();
}
return convertView;
}
#Override
public boolean isChildSelectable(int groupPosition, int childPosition) {
return true;
}
}
Problem is i have mobile in which jellybean is installed.In the jellybean or lower of jellybean it's not comes in the order.If same code i ran into lollipop or marshmallow it's comes into the order.Order like
trieseries_2016_g1
trieseries_2016_g2
until trieseries_2016_final
Here is a screenshort of marshmallow
please, help me to solve out this problem.
Here is a sceenshort of jellybean

My AsyncTask not getting cancelled android

I am working on a task that calls my AsyncTask , once the async task is executed , I wait for 20 seconds to get the data from server , if it is still loading I am cancelling it (handling timeout)
public void handleServerTimeOut() {
getStore = new GetStore();
getStore.execute();
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
if (getStore != null && getStore.getStatus() != AsyncTask.Status.FINISHED) {
boolean result = getStore.cancel(true);
Log.e(TAG, " handleServerTimeOut() reached 20 seconds");
Log.e(TAG, "" + result);
}
}
}, 20000);
}
AsyncTask
class GetStore extends AsyncTask<Void, Void, String> {
String status, message;
JSONArray jsonArray;
String buildingIdGuest, buildingIdUser, finalBuildingID;
#Override
protected void onPreExecute() {
super.onPreExecute();
if (isCancelled()) {
return;
} else {
buildingIdUser = utilClass.getSharePerefernce(getActivity(), KEY_BUILDING_ID_USER, "");
buildingIdGuest = utilClass.getSharePerefernce(getActivity(), KEY_BUILDING_ID_GUEST, "");
if (buildingIdUser.equals("0") || buildingIdUser.equals("")) {
finalBuildingID = buildingIdGuest;
} else {
finalBuildingID = buildingIdUser;
}
error_flag = 0;
gridView.setVisibility(View.VISIBLE);
error_layout.setVisibility(View.INVISIBLE);
img_no_internet.setVisibility(View.INVISIBLE);
img_no_results.setVisibility(View.INVISIBLE);
img_server_error.setVisibility(View.INVISIBLE);
progressDialog.setMessage("Getting nearby stores ...");
progressDialog.setIndeterminate(true);
progressDialog.setCancelable(true);
progressDialog.show();
}
}
#Override
protected String doInBackground(Void... params) {
if (NetworkCheck.isNetworkAvailable(getActivity())) {
try {
jsonObj = userFunction.getStores(OS, MAKE, MODEL, finalBuildingID);
Log.e(TAG, jsonObj.toString());
status = jsonObj.getString("status");
message = jsonObj.getString("message");
if (status.equalsIgnoreCase("success")) {
jsonArray = jsonObj.getJSONArray("response");
for (int i = 0; i < jsonArray.length(); i++) {
gridModel = new GridModel();
gridModel.setId(jsonArray.getJSONObject(i).getString("id"));
gridModel.setStore_name(jsonArray.getJSONObject(i).getString("name"));
gridModel.setImage_name(jsonArray.getJSONObject(i).getString("image_name"));
gridListData.add(gridModel);
}
Log.e(TAG, "****** = " + gridListData.toString());
} else if (status.equalsIgnoreCase("invalid parameters")) {
error_flag = 2;
Log.e(TAG, "invalid parameters");
} else if (status.equalsIgnoreCase("no stores")) {
error_flag = 3;
Log.e(TAG, "No Data");
}
Log.e(TAG, "****** status " + status);
return String.valueOf(jsonObj);
} catch (Exception e) {
error_flag = 1; // Handling server timeout.
getActivity().runOnUiThread(new Runnable() {
#Override
public void run() {
progressDialog.dismiss();
return;
}
});
Log.e(TAG, e.toString());
}
} else {
Log.e(TAG, "Network Error");
error_flag = 1;
}
return null;
}
#Override
protected void onPostExecute(String response) {
super.onPostExecute(response);
Log.e(TAG, " **** error **** " + error_flag);
if (error_flag == 1) {
gridView.setVisibility(View.GONE);
error_layout.setVisibility(View.VISIBLE);
img_no_internet.setVisibility(View.VISIBLE);
} else if (error_flag == 2) {
gridView.setVisibility(View.GONE);
error_layout.setVisibility(View.VISIBLE);
img_server_error.setVisibility(View.VISIBLE);
txtError.setVisibility(View.VISIBLE);
txtError.setText(message);
} else if (error_flag == 3) {
gridView.setVisibility(View.GONE);
error_layout.setVisibility(View.VISIBLE);
img_no_results.setVisibility(View.VISIBLE);
}
gridAdapter = new GridAdapter(getActivity(), gridListData);
gridView.setAdapter(gridAdapter);
if ((progressDialog != null) && progressDialog.isShowing()) {
progressDialog.dismiss();
}
}
}
I also wanted to cancel my AsyncTask when the user cancels the ProgressDialog
You are checking isCancelled() only once in your AsyncTask - in the onPreExecute() method. At the time you call cancel() on your task instance, this check has already been evaluated and this is why the async task is still completing and updating the UI.
To deal with the issue, I suggest you include more checks for cancellation, using the isCancelled() method. One obvious place to include such a check is in the onPostExecute() method, right before you update the UI. You could also include a check before making the actual request to the server, after receiving the response, etc.

How to stop Get data when orientation changes for selecting Checkbox

In my screen i am showing checkboxes with response of using GET when it is getting 0 means setchecked(false) and when it is getting 1 means setchecked(true).
Problem:
Consider when i am selected Multiple checkboxes and changed my
orientation the fragment is getting reloaded and it binding data from
GET method .How to overcome this problem .I am posting my code on
below .
#Override
public void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
if(savedInstanceState!=null)
{
cBox_furnishing.setChecked(savedInstanceState.getBoolean("Furnish"));
cBox_washMachine.setChecked(savedInstanceState.getBoolean("washMachine"));
cBox_ac.setChecked(savedInstanceState.getBoolean("ac"));
cBox_microwaveOven.setChecked(savedInstanceState.getBoolean("microwaveOven"));
cBox_ctv.setChecked(savedInstanceState.getBoolean("ctv"));
cBox_refrigerator.setChecked(savedInstanceState.getBoolean("refrigerator"));
cBox_tw.setChecked(savedInstanceState.getBoolean("tw"));
cBox_music.setChecked(savedInstanceState.getBoolean("music"));
cBox_pc.setChecked(savedInstanceState.getBoolean("pc"));
cBox_car.setChecked(savedInstanceState.getBoolean("car"));
}
Fragment_resident_info.leadno = getArguments().getString("LeadNo");
getdata();
}
#Override
public void onSaveInstanceState(Bundle savedInstanceState)
{
b_furnishing_CHECK = cBox_furnishing.isChecked();
b_washMachine_CHECK = cBox_washMachine.isChecked();
b_ac_CHECK = cBox_ac.isChecked();
b_microwaveOven_CHECK = cBox_microwaveOven.isChecked();
b_ctv_CHECK = cBox_ctv.isChecked();
b_refrigerator_CHECK = cBox_refrigerator.isChecked();
b_tw_CHECK = cBox_tw.isChecked();
b_music_CHECK = cBox_music.isChecked();
b_pc_CHECK = cBox_pc.isChecked();
b_car_CHECK = cBox_car.isChecked();
savedInstanceState.putBoolean("Furnish", b_furnishing_CHECK);
savedInstanceState.putBoolean("washMachine", b_washMachine_CHECK);
savedInstanceState.putBoolean("ac", b_ac_CHECK);
savedInstanceState.putBoolean("microwaveOven", b_microwaveOven_CHECK);
savedInstanceState.putBoolean("ctv", b_ctv_CHECK);
savedInstanceState.putBoolean("refrigerator", b_refrigerator_CHECK);
savedInstanceState.putBoolean("tw", b_tw_CHECK);
savedInstanceState.putBoolean("music", b_music_CHECK);
savedInstanceState.putBoolean("pc", b_pc_CHECK);
savedInstanceState.putBoolean("car", b_car_CHECK);
super.onSaveInstanceState(savedInstanceState);
}
private BroadcastReceiver reciever_assetseen = new BroadcastReceiver()
{
#Override
public void onReceive(Context context, Intent intent) {
String response = intent.getStringExtra("httpResponse");
try
{
JSONArray ary = new JSONArray(response);
JSONObject obj = ary.getJSONObject(0);
String st_furnishing = obj.getString("Residence_Furnish");
String st_washingmachine = obj.getString("Washing_Machine");
String st_Ac = obj.getString("AC");
String st_microwaveoven = obj.getString("Microwave_Oven");
String st_ctv = obj.getString("CTV");
String st_refridge = obj.getString("Refrigerator");
String st_tw = obj.getString("TW");
String st_music = obj.getString("Music");
String st_pc = obj.getString("PC");
String st_car = obj.getString("CAR");
if(b_furnishing_CHECK == true)
{
cBox_furnishing.setChecked(true);
}
else if(st_furnishing.equals("0") || st_furnishing.equals("null") )
{
cBox_furnishing.setChecked(false);
}
else
{
cBox_furnishing.setChecked(true);
}
if(b_washMachine_CHECK == true)
{
cBox_washMachine.setChecked(true);
}
else if(st_washingmachine.equals("0") || st_washingmachine.equals("null") )
{
cBox_washMachine.setChecked(false);
}
else
{
cBox_washMachine.setChecked(true);
}
if( b_ac_CHECK == true)
{
cBox_ac.setChecked(true);
}
else if(st_Ac.equals("0")|| st_Ac.equals("null"))
{
cBox_ac.setChecked(false);
}
else
{
cBox_ac.setChecked(true);
}
if( b_microwaveOven_CHECK == true)
{
cBox_microwaveOven.setChecked(true);
}
else if(st_microwaveoven.equals("0") || st_microwaveoven.equals("null") )
{
cBox_microwaveOven.setChecked(false);
}
else
{
cBox_microwaveOven.setChecked(true);
}
if( b_ctv_CHECK == true)
{
cBox_ctv.setChecked(true);
}
else if(st_ctv.equals("0")|| st_ctv.equals("null") )
{
cBox_ctv.setChecked(false);
}
else
{
cBox_ctv.setChecked(true);
}
if( b_refrigerator_CHECK == true)
{
cBox_refrigerator.setChecked(true);
}
else if(st_refridge.equals("0")|| st_refridge.equals("null") )
{
cBox_refrigerator.setChecked(false);
}
else
{
cBox_refrigerator.setChecked(true);
}
if( b_tw_CHECK == true)
{
cBox_tw.setChecked(true);
}
else if(st_tw.equals("0")|| st_tw.equals("null") )
{
cBox_tw.setChecked(false);
}
else
{
cBox_tw.setChecked(true);
}
if( b_music_CHECK == true)
{
cBox_music.setChecked(true);
}
else if(st_music.equals("0")|| st_music.equals("null"))
{
cBox_music.setChecked(false);
}
else
{
cBox_music.setChecked(true);
}
if( b_pc_CHECK == true)
{
cBox_pc.setChecked(true);
}
else if(st_pc.equals("0")|| st_pc.equals("null") )
{
cBox_pc.setChecked(false);
}
else
{
cBox_pc.setChecked(true);
}
if( b_car_CHECK == true)
{
cBox_car.setChecked(true);
}
else if(st_car.equals("0")|| st_car.equals("null"))
{
cBox_car.setChecked(false);
}
else
{
cBox_car.setChecked(true);
}
}
catch(Exception e)
{
}
}
};
if(savedInstanceState!=null)
{
cBox_furnishing.setChecked(savedInstanceState.getBoolean("Furnish"));
cBox_washMachine.setChecked(savedInstanceState.getBoolean("washMachine"));
cBox_ac.setChecked(savedInstanceState.getBoolean("ac"));
cBox_microwaveOven.setChecked(savedInstanceState.getBoolean("microwaveOven"));
cBox_ctv.setChecked(savedInstanceState.getBoolean("ctv"));
cBox_refrigerator.setChecked(savedInstanceState.getBoolean("refrigerator"));
cBox_tw.setChecked(savedInstanceState.getBoolean("tw"));
cBox_music.setChecked(savedInstanceState.getBoolean("music"));
cBox_pc.setChecked(savedInstanceState.getBoolean("pc"));
cBox_car.setChecked(savedInstanceState.getBoolean("car"));
}else{
Fragment_resident_info.leadno = getArguments().getString("LeadNo");
getdata();
}

Categories

Resources