I want to get HashMap which is being passed through Bundle from a AsyncTask. But I am getting NullPointerException.
Flow is like below...
FragmentMainActivity -> TableScreenSectionwiseActivity -> GetSectionsAsync
HashMap is passed from GetSectionsAsync to TableScreenSectionwiseActivity through Bundle.
Note: FragmentMainActivity is FragmentActivity.TableScreenSectionwiseActivity is Fragment.GetSectionsAsync is a AsyncTask.
What I have tried, is like below.
Error I getting...
Error Image
TableScreenSectionwiseActivity.java
package com.malaka.ui;
import java.util.ArrayList;
import java.util.HashMap;
import adapters.table_section_adapter;
import android.graphics.Color;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;
import com.malaka.R;
import com.malaka.helper.ActionItem;
import com.malaka.helper.GetSectionsGetterSetter;
import com.malaka.helper.Logout;
import com.malaka.helper.PopupWindows;
import com.malaka.helper.QuickAction;
import com.malaka.helper.QuickActionLocation;
import com.malaka.helper.ReplaceFragment;
import com.malaka.helper.async.GetSectionsAsync;
import com.malaka.helper.async.TableStatusAsync;
import com.malaka.utils.PreferenceUtils;
public class TableScreenSectionwiseActivity extends Fragment implements
OnItemClickListener {
final static String TAG = "TableScreenSectionwiseActivity";
private static final int ID_TABLE = 1;
private static final int ID_TASK = 2;
private static final int ID_MANAGER = 3;
private static final int ID_RECIPE = 4;
private static final int ID_INSTRUCTION = 5;
private static final int ID_SEARCH = 6;
private static final int ID_HELP = 7;
private static final int ID_SETTING = 8;
private static final int ID_LOGOUT = 9;
private static final int ID_KP = 10;
private static final int ID_BANER = 20;
private static final int ID_CITY = 30;
String[] values = new String[] { "1", "2" };
public static FragmentActivity activity;
RelativeLayout rl;
static PreferenceUtils pref;
QuickAction quickAction;
QuickActionLocation quickActionLocation;
HashMap<String, ArrayList<String>> map1;
ArrayList<String> ids, names;
ListView section_list;
TextView version, malaka;
ImageView refresh;
Animation rotation;
private TextView mDropdownTitle;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.table_screen_sectionwise,
container, false);
init(view);
return view;
}
private void init(View view) {
activity = getActivity();
pref = new PreferenceUtils(getActivity());
malaka = (TextView) view
.findViewById(R.id.txt_malaka_title_table_sectionwise);
malaka.setText(pref.getLocation());
if (!pref.getSectionStatus()) {
GetSectionsAsync getSectionsAsync = new GetSectionsAsync(
getActivity());
HashMap<String, String> map = new HashMap<String, String>();
map.put("Location_Name", pref.getLocation());
getSectionsAsync.execute(map);
}
Bundle bundle = new Bundle();
Log.e("Bundle Size: ", bundle.size() + "");
map1 = (HashMap<String, ArrayList<String>>) getArguments()
.getSerializable("SECTIONS_HASHMAP");
GetSectionsGetterSetter.setData(map1);
ids = map1.get("ID_LIST");
names = map1.get("NAME_LIST");
for (int i = 0; i < names.size(); i++) {
Log.e("Names: ", names.get(i));
}
section_list = (ListView) view
.findViewById(R.id.section_name_list_view);
table_section_adapter adapter = new table_section_adapter(
activity.getApplicationContext(), values);
section_list.setAdapter(adapter);
section_list.setOnItemClickListener(this);
rl = (RelativeLayout) view.findViewById(R.id.ll_location_sectionwise);
if (pref.getUserRole()) {
rl.setVisibility(View.VISIBLE);
} else {
rl.setVisibility(View.GONE);
}
rl.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
quickActionLocation.show(arg0);
}
});
version = (TextView) view.findViewById(R.id.table_version_sectionwise);
version.setText(pref.getVersion());
rotation = AnimationUtils.loadAnimation(getActivity(),
R.anim.refresh_dialog);
refresh = (ImageView) view
.findViewById(R.id.img_refresh_table_sectionwise);
refresh.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
refresh.startAnimation(rotation);
TableStatusAsync Async = new TableStatusAsync(getActivity());
HashMap<String, String> map = new HashMap<String, String>();
map.put("UserId", pref.getUserId());
map.put("SectionId", "0");
map.put("Location", pref.getLocation());
Async.execute(map);
}
});
ActionItem tableItem = new ActionItem(ID_TABLE, "Table Status");
ActionItem taskItem = new ActionItem(ID_TASK, "My Tasks");
ActionItem managerItem = new ActionItem(ID_MANAGER, "Manager");
ActionItem recipeItem = new ActionItem(ID_RECIPE, "Recipes");
ActionItem instItem = new ActionItem(ID_INSTRUCTION, "Instructions");
ActionItem searchItem = new ActionItem(ID_SEARCH, "Search");
ActionItem helpItem = new ActionItem(ID_HELP, "Help");
ActionItem settingItem = new ActionItem(ID_SETTING, "Settings");
ActionItem logoutItem = new ActionItem(ID_LOGOUT, "Logout");
ActionItem kpItem = new ActionItem(ID_KP, "Koregaon Park");
ActionItem cityItem = new ActionItem(ID_CITY, "Phoneix Market");
ActionItem banerItem = new ActionItem(ID_BANER, "Baner");
quickActionLocation = new QuickActionLocation(getActivity(),
QuickActionLocation.VERTICAL);
quickActionLocation.addActionItem(kpItem, Color.WHITE);
quickActionLocation.addActionItem(cityItem, Color.WHITE);
quickActionLocation.addActionItem(banerItem, Color.WHITE);
// use setSticky(true) to disable QuickAction dialog being dismissed
// after an item is clicked
// tableItem.setSticky(true);
// create QuickAction. Use QuickAction.VERTICAL or
// QuickAction.HORIZONTAL param to define layout
// orientation
quickAction = new QuickAction(getActivity(), QuickAction.VERTICAL);
// add action items into QuickAction
quickAction.addActionItem(tableItem, Color.WHITE);
quickAction.addActionItem(taskItem, Color.parseColor("#F2A523"));
if (pref.getUserRole()) {
quickAction.addActionItem(managerItem, Color.parseColor("#F2A523"));
}
if (pref.getRecipeScreenStatus()) {
quickAction.addActionItem(recipeItem, Color.parseColor("#F2A523"));
}
quickAction.addActionItem(instItem, Color.parseColor("#F2A523"));
quickAction.addActionItem(searchItem, Color.parseColor("#F2A523"));
quickAction.addActionItem(helpItem, Color.parseColor("#F2A523"));
quickAction.addActionItem(settingItem, Color.parseColor("#F2A523"));
quickAction.addActionItem(logoutItem, Color.parseColor("#F2A523"));
// Set listener for action item clicked
quickAction
.setOnActionItemClickListener(new QuickAction.OnActionItemClickListener() {
#Override
public void onItemClick(QuickAction source, int pos,
int actionId) {
ActionItem actionItem = quickAction.getActionItem(pos);
quickAction.dismiss();
// here we can filter which action item was clicked with
// pos or actionId parameter
if (actionId == ID_TABLE) {
closeDropdown();
} else if (actionId == ID_TASK) {
closeDropdown();
ReplaceFragment.getReplaceFragment(getActivity(),
new TaskLeadingActivity(), "left");
} else if (actionId == ID_MANAGER) {
closeDropdown();
ReplaceFragment.getReplaceFragment(getActivity(),
new ManagerPageActivity(), "left");
} else if (actionId == ID_RECIPE) {
closeDropdown();
ReplaceFragment.getReplaceFragment(getActivity(),
new ReceipiesScreenActivity(), "left");
} else if (actionId == ID_INSTRUCTION) {
closeDropdown();
ReplaceFragment.getReplaceFragment(getActivity(),
new InstructionActivity(), "left");
} else if (actionId == ID_SEARCH) {
closeDropdown();
} else if (actionId == ID_HELP) {
closeDropdown();
} else if (actionId == ID_SETTING) {
closeDropdown();
ReplaceFragment.getReplaceFragment(getActivity(),
new SettingScreenActivity(), "left");
} else if (actionId == ID_LOGOUT) {
closeDropdown();
Logout logout = new Logout(getActivity());
}
}
});
// set listnener for on dismiss event, this listener will be called only
// if QuickAction dialog was dismissed
// by clicking the area outside the dialog.
quickAction.setOnDismissListener(new QuickAction.OnDismissListener() {
#Override
public void onDismiss() {
// Toast.makeText(getActivity(), "Dismissed",
// Toast.LENGTH_SHORT).show();
closeDropdown();
}
});
// Set listener for action item clicked
quickActionLocation
.setOnActionItemClickListener(new QuickActionLocation.OnActionItemClickListener() {
#Override
public void onItemClick(QuickActionLocation source,
int pos, int actionId) {
ActionItem actionItem = quickActionLocation
.getActionItem(pos);
quickActionLocation.dismiss();
// here we can filter which action item was clicked with
// pos or actionId parameter
if (actionId == ID_KP) {
getTableStatus("Koregaon Park");
} else if (actionId == ID_CITY) {
getTableStatus("Phoneix Market City");
} else if (actionId == ID_BANER) {
getTableStatus("Baner");
}
}
});
mDropdownTitle = ((TextView) view
.findViewById(R.id.dropdown_textview_table_sectionwise));
mDropdownTitle.setText(pref.getUserNameToGetManagerPage()
.substring(0, 1).toUpperCase()
+ pref.getUserNameToGetManagerPage().substring(1).toLowerCase()
+ " ");
final TextView dropDownTextView = (TextView) view
.findViewById(R.id.dropdown_textview_table_sectionwise);
dropDownTextView.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
if (PopupWindows.mWindow.isShowing()) {
closeDropdown();
} else {
openDropdown();
}
quickAction.show(v);
}
});
}
public void getTableStatus(String location) {
pref.setLocation(location);
Log.e(TAG, "location : " + pref.getLocation());
TableStatusAsync Async = new TableStatusAsync(getActivity());
HashMap<String, String> map = new HashMap<String, String>();
map.put("UserId", pref.getUserId());
map.put("SectionId", "0");
map.put("Location", pref.getLocation());
Async.execute(map);
}
private void openDropdown() {
mDropdownTitle.setCompoundDrawablesWithIntrinsicBounds(0, 0,
R.drawable.arrow_up, 0);
}
private void closeDropdown() {
mDropdownTitle.setCompoundDrawablesWithIntrinsicBounds(0, 0,
R.drawable.arrow_down, 0);
}
#Override
public void onItemClick(AdapterView<?> parent, View view, int position,
long id) {
Toast.makeText(activity, "Clicked" + position, Toast.LENGTH_SHORT)
.show();
}
}
GetSectionsAsync.java
package com.malaka.helper.async;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import org.ksoap2.SoapEnvelope;
import org.ksoap2.serialization.PropertyInfo;
import org.ksoap2.serialization.SoapObject;
import org.ksoap2.serialization.SoapSerializationEnvelope;
import org.ksoap2.transport.HttpTransportSE;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.util.Log;
import com.malaka.helper.AsyncAttributes;
import com.malaka.helper.ReplaceFragment;
import com.malaka.helper.TableStatusXmlParser;
import com.malaka.ui.CustomerDetailsActivity;
import com.malaka.ui.TableScreenSectionwiseActivity;
import com.malaka.utils.CommanUtils;
import com.malaka.utils.NetworkUtils;
import com.malaka.utils.PreferenceUtils;
public class GetSectionsAsync extends
AsyncTask<Map<String, String>, Void, Void> {
final static String TAG = "GetSectionsAsync";
FragmentActivity context;
String xml;
HashMap<String, ArrayList<String>> details;
PreferenceUtils pref;
int response;
boolean isConnected;
public GetSectionsAsync(FragmentActivity context) {
this.context = context;
pref = new PreferenceUtils(context);
}
#Override
protected void onPreExecute() {
super.onPreExecute();
CommanUtils.getDialogShow(context, "Please Wait...");
}
#Override
protected Void doInBackground(Map<String, String>... params) {
if (NetworkUtils.isConnectedToInternet(context)) {
isConnected = true;
HashMap<String, String> map = (HashMap<String, String>) params[0];
SoapObject request = new SoapObject(
AsyncAttributes.GetSecNAMESPACE,
AsyncAttributes.GetSecMETHOD_NAME);
Iterator<String> iterator = map.keySet().iterator();
PropertyInfo pi = new PropertyInfo();
pi.setName("RLocation");
pi.setValue(map.get("Location_Name"));
pi.setType(String.class);
request.addProperty(pi);
while (iterator.hasNext()) {
String key = iterator.next();
request.addProperty(key, map.get(key));
Log.e(TAG, "user id key: " + key + " value: " + map.get(key));
}
SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(
SoapEnvelope.VER11);
envelope.dotNet = true;
envelope.setOutputSoapObject(request);
HttpTransportSE androidHttpTransport = new HttpTransportSE(
AsyncAttributes.GetSecURL);
try {
androidHttpTransport.call(AsyncAttributes.GetSecSOAP_ACTION,
envelope);
SoapObject result = (SoapObject) envelope.bodyIn;
if (result
.toString()
.equals("GetSectionsForLocationResponse{GetSectionsForLocationResult=Failur; }")) {
String xmltemp = String.valueOf(result).split("=")[1];
xml = xmltemp.split(";")[0];
} else {
String xmltemp = "<NewDataSet>\n"
+ String.valueOf(result).split("<NewDataSet>")[1];
xml = xmltemp.split("</NewDataSet>")[0] + "</NewDataSet>";
}
} catch (Exception e) {
e.printStackTrace();
}
if (xml == null) {
response = 1;
Log.e(TAG, "xml null");
} else if (xml.equals("No Table available")) {
response = 2;
} else {
response = 2;
Log.e(TAG, "Task 1 result " + xml);
details = TableStatusXmlParser.getSectionsXml(xml, context);
}
} else {
isConnected = false;
}
return null;
}
protected void onPostExecute(Void result) {
super.onPostExecute(result);
CommanUtils.getDialogDismiss();
if (!isConnected) {
CommanUtils.showAlertDialog("Internet Is Required", context);
} else if (response == 1) {
CommanUtils.getToast("Server Error", context);
}
if (response == 2) {
pref.setSectionStatus(true);
goAhead();
}
}
private void goAhead() {
Bundle bundle = new Bundle();
bundle.putSerializable("SECTIONS_HASHMAP", details);
Fragment fragment = new TableScreenSectionwiseActivity();
fragment.setArguments(bundle);
ReplaceFragment.getReplaceFragment(context, fragment, "");
}
}
If you guys want FragmentMainActivity code. I can put it. But I dont think so it is required. Thanks in advance.
At the end I have achieved it through INTERFACE.
Just do like below...
Make interface in GetSectionsAsync.java named FragmentInterfaceCallBack and declare a method named onTaskCompleted().
Now define a method in GetSectionsAsync.java named setFragmentInterfaceCallBack which will set the interface's object while calling from TableScreenSectionwiseActivity.java.
Now in onPostExecute method write below code....interfaceCallBack.onTaskCompleted(details); details is a data received from web service.
Go to TableScreenSectionwiseActivity.java and implements FragmentInterfaceCallBack, define it's onTaskCompleted() method and add below code to TableScreenSectionwiseActivity.java where you are calling AsyncTask getSectionsAsync.setFragmentInterfaceCallBack(this); where getSectionsAsync is a object of GetSectionsAsync.java.
In onTaskCompleted() method you get your desire data.
I have made below changes in my both files.
GetSectionsAsync.java
Making interface and defining setFragmentInterfaceCallBack() method....
private FragmentInterfaceCallBack interfaceCallBack;
public interface FragmentInterfaceCallBack {
public void onTaskCompleted(HashMap<String, ArrayList<String>> map);
}
public void setFragmentInterfaceCallBack(
FragmentInterfaceCallBack _interfaceCallBack) {
this.interfaceCallBack = _interfaceCallBack;
}
In onPostExecute method....
protected void onPostExecute(Void result) {
super.onPostExecute(result);
CommanUtils.getDialogDismiss();
if (!isConnected) {
CommanUtils.showAlertDialog("Internet Is Required", context);
} else if (response == 1) {
CommanUtils.getToast("Server Error", context);
}
if (response == 2) {
pref.setSectionStatus1(true);
// goAhead();
}
interfaceCallBack.onTaskCompleted(details);
}
TableScreenSectionwiseActivity.java
Implementing interface....
public class TableScreenSectionwiseActivity extends Fragment implements OnItemClickListener, FragmentInterfaceCallBack {
Calling AsyncTask....
if (!pref.getSectionStatus1()) {
Log.e("Once Again in TableScreenSectionwiseActivity: ", "hmm....");
GetSectionsAsync getSectionsAsync = new GetSectionsAsync(
getActivity());
getSectionsAsync.setFragmentInterfaceCallBack(this);
HashMap<String, String> map = new HashMap<String, String>();
map.put("Location_Name", pref.getLocation());
getSectionsAsync.execute(map);
}
Defining interface's method....
#Override
public void onTaskCompleted(HashMap<String, ArrayList<String>> hashMap) {
ids = hashMap.get("ID_LIST");
names = hashMap.get("NAME_LIST");
table_section_adapter adapter = new table_section_adapter(
activity.getApplicationContext(), names, ids);
section_list.setAdapter(adapter);
section_list.setOnItemClickListener(this);
}
That's it. Hope this will help someone..
Map<String, String> map = ((Bundle)appRestrictions.get(key)).keySet().stream().collect(Collectors.toMap(x -> x, x -> bundle.get(x).toString()));
JSONObject jsonNested = new JSONObject(map);
Related
I am new to Android development, I am working on a App and I want to convert my below mentioned code to AnsyncTask. Because it is showing me Run-time error that I am doing too much work on UI thread. Please help me to convert it to AnsyncTask.
import android.app.ProgressDialog;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.os.SystemClock;
import android.support.v7.app.AppCompatActivity;
import android.view.Gravity;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.GridView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import org.w3c.dom.Text;
import java.lang.reflect.Array;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Random;
import java.util.Timer;
import java.util.TimerTask;
public class PlayActivity extends AppCompatActivity {
GridView gridview;
TextView textView;
TextView result;
TextView remainingChance;
Button giveup;
Button goback;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.play);
textView = (TextView) findViewById(R.id.blanks);
result = (TextView) findViewById(R.id.result);
remainingChance = (TextView) findViewById(R.id.remainingChance);
giveup = (Button) findViewById(R.id.giveup);
goback = (Button) findViewById(R.id.goback);
goback.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent goBack = new Intent(PlayActivity.this, MainActivity.class);
startActivity(goBack);
}
});
String dash = "";
Intent intent = getIntent();
Bundle bundle = intent.getExtras();
String easyArray[] = bundle.getStringArray("easy");
final String randomStr = easyArray[new Random().nextInt(easyArray.length)]; // Getting a random string from Array
giveup.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
result.setText(randomStr); // By clicking on Give up button, it displays the actual word & a message Go Back and try again
remainingChance.setText("Go Back and try again");
}
});
final Integer strLength = randomStr.length();
// Creating string with question mark with 2nd and 5th character only
for(int i=1; i<=strLength; i++){
if(i == 2){
dash = dash+Character.toString(randomStr.charAt(1));
} else if (i == 5){
dash = dash+ Character.toString(randomStr.charAt(4));
} else {
dash = dash + "?";
}
}
final String displayVal = dash;
textView.setText(displayVal); // Displaying string with question mark with 2nd and 5th character only
gridview = (GridView) findViewById(R.id.gridview);
final String[] mAlphabets = new String[]{"A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z"};
final ArrayList<String> array_list = new ArrayList<String>(Arrays.asList(mAlphabets));
final ArrayAdapter arrayAdapter = new ArrayAdapter (getApplicationContext(),android.R.layout.simple_list_item_1,array_list);
gridview.setNumColumns(8);
gridview.setBackgroundColor(Color.BLUE);
gridview.setGravity(Gravity.CENTER);
gridview.setAdapter(arrayAdapter);
gridview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
String finalDisplayVal = displayVal;
int count = 0;
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
final ProgressDialog mProgressDialog = new ProgressDialog(PlayActivity.this);
// Set progressdialog title
mProgressDialog.setTitle("Loading...");
// Set progressdialog message
mProgressDialog.setMessage("Checkinggg...");
mProgressDialog.setIndeterminate(false);
// Show progressdialog
mProgressDialog.show();
long delayInMillis = 1000;
Timer timer = new Timer();
timer.schedule(new TimerTask() {
#Override
public void run() {
mProgressDialog.dismiss();
}
}, delayInMillis);
String itemValue = (String) gridview.getItemAtPosition(position);
array_list.remove(position); // Removing character from 26 alphabets which is clicked by user
arrayAdapter.notifyDataSetChanged(); // Reset gridview
if(randomStr.contains(itemValue)){ // If selected alphabets exists in string
for(int k=0; k<strLength; k++){
if(Character.toString(randomStr.charAt(k)).equalsIgnoreCase(itemValue)){
int charPos = randomStr.indexOf(itemValue);
while(charPos >= 0){
finalDisplayVal = replaceCharAt(finalDisplayVal, charPos, itemValue);
textView.setText(finalDisplayVal);
charPos = randomStr.indexOf(itemValue, charPos + 1);
}
}
}
checkWinCount(); // Checking if User Wins
} else {
count++;
int remVal = 4-count;
remainingChance.setText("Not Exist, You have " + remVal + " chance(s) left.");
}
checkLoseCount(); // Checking if User Lose
}
public String replaceCharAt(String s, int pos, String c) {
return s.substring(0, pos) + c + s.substring(pos + 1);
}
public void checkLoseCount() {
if(count > 3) {
Toast.makeText(PlayActivity.this, "You Loose, Value is: "+randomStr, Toast.LENGTH_LONG).show();
Intent goBack = new Intent(PlayActivity.this, MainActivity.class);
startActivity(goBack);
}
}
public void checkWinCount(){
if(randomStr.equalsIgnoreCase(finalDisplayVal)){
Toast.makeText(PlayActivity.this, "Hurray!!! You WIN... It's "+randomStr, Toast.LENGTH_LONG).show();
Intent goBack = new Intent(PlayActivity.this, MainActivity.class);
startActivity(goBack);
}
}
});
}
}
AsyncTask Code;
import android.app.ProgressDialog;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.Gravity;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.GridView;
import android.widget.TextView;
import android.widget.Toast;
import android.os.AsyncTask;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Random;
import java.util.Timer;
import java.util.TimerTask;
public class PlayActivity1 extends AppCompatActivity {
GridView gridview;
TextView textView;
TextView result;
TextView remainingChance;
Button giveup;
Button goback;
int count = 0;
String randomStr;
String finalDisplayVal;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.play);
textView = (TextView) findViewById(R.id.blanks);
result = (TextView) findViewById(R.id.result);
remainingChance = (TextView) findViewById(R.id.remainingChance);
giveup = (Button) findViewById(R.id.giveup);
goback = (Button) findViewById(R.id.goback);
goback.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent goBack = new Intent(PlayActivity1.this, MainActivity.class);
startActivity(goBack);
}
});
String dash = "";
Intent intent = getIntent();
Bundle bundle = intent.getExtras();
String easyArray[] = bundle.getStringArray("easy");
final String randomStr = easyArray[new Random().nextInt(easyArray.length)]; // Getting a random string from Array
giveup.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
result.setText(randomStr); // By clicking on Give up button, it displays the actual word & a message Go Back and try again
remainingChance.setText("Go Back and try again");
}
});
final Integer strLength = randomStr.length();
// Creating string with question mark with 2nd and 5th character only
for (int i = 1; i <= strLength; i++) {
if (i == 2) {
dash = dash + Character.toString(randomStr.charAt(1));
} else if (i == 5) {
dash = dash + Character.toString(randomStr.charAt(4));
} else {
dash = dash + "?";
}
}
final String displayVal = dash;
textView.setText(displayVal); // Displaying string with question mark with 2nd and 5th character only
gridview = (GridView) findViewById(R.id.gridview);
final String[] mAlphabets = new String[]{"A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z"};
final ArrayList<String> array_list = new ArrayList<String>(Arrays.asList(mAlphabets));
final ArrayAdapter arrayAdapter = new ArrayAdapter(getApplicationContext(), android.R.layout.simple_list_item_1, array_list);
gridview.setNumColumns(8);
gridview.setBackgroundColor(Color.BLUE);
gridview.setGravity(Gravity.CENTER);
gridview.setAdapter(arrayAdapter);
gridview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
AsyncTaskRunner runner = new AsyncTaskRunner();
String finalDisplayVal = displayVal;
runner.execute(finalDisplayVal);
String itemValue = (String) gridview.getItemAtPosition(position);
array_list.remove(position); // Removing character from 26 alphabets which is clicked by user
arrayAdapter.notifyDataSetChanged(); // Reset gridview
if (randomStr.contains(itemValue)) { // If selected alphabets exists in string
for (int k = 0; k < strLength; k++) {
if (Character.toString(randomStr.charAt(k)).equalsIgnoreCase(itemValue)) {
int charPos = randomStr.indexOf(itemValue);
while (charPos >= 0) {
finalDisplayVal = replaceCharAt(finalDisplayVal, charPos, itemValue);
textView.setText(finalDisplayVal);
charPos = randomStr.indexOf(itemValue, charPos + 1);
}
}
}
checkWinCount(); // Checking if User Wins
} else {
count++;
int remVal = 4 - count;
remainingChance.setText("Not Exist, You have " + remVal + " chance(s) left.");
}
checkLoseCount(); // Checking if User Lose
}
});
}
public String replaceCharAt(String s, int pos, String c) {
return s.substring(0, pos) + c + s.substring(pos + 1);
}
public void checkLoseCount() {
if (count > 3) {
Toast.makeText(PlayActivity1.this, "You Loose, Value is: " + randomStr, Toast.LENGTH_LONG).show();
Intent goBack = new Intent(PlayActivity1.this, MainActivity.class);
startActivity(goBack);
}
}
public void checkWinCount() {
if (randomStr.equalsIgnoreCase(finalDisplayVal)) {
Toast.makeText(PlayActivity1.this, "Hurray!!! You WIN... It's " + randomStr, Toast.LENGTH_LONG).show();
Intent goBack = new Intent(PlayActivity1.this, MainActivity.class);
startActivity(goBack);
}
}
private class AsyncTaskRunner extends AsyncTask<String, String, ProgressDialog> {
#Override
protected ProgressDialog doInBackground(String... params) {
final ProgressDialog mProgressDialog = new ProgressDialog(PlayActivity1.this);
// Set progressdialog title
mProgressDialog.setTitle("Loading...");
// Set progressdialog message
mProgressDialog.setMessage("Checkinggg...");
mProgressDialog.setIndeterminate(false);
// Show progressdialog
mProgressDialog.show();
try {
long delayInMillis = 1000;
Timer timer = new Timer();
timer.schedule(new TimerTask() {
#Override
public void run() {
mProgressDialog.dismiss();
}
}, delayInMillis);
}catch (Exception e){
e.printStackTrace();
}
return mProgressDialog;
}
}
}
Hi I have an Activity which user open upon click on a TAB. Actually I have a ViewGroup and Tabactivity as Main Activity. on the first tab I have three activity.
Now in an activity I have a list view (custom) populating on Oncreate and a ViewFlipper (only adding view) in Onresume using AsyncTask.
In that asynctask in Pre Execute if I add code for loader it gives error. Also If I do not show the loader the screen is freezing until the Async task finished.
I actually want to load the list view first and then in background run the async task with a loader. Also does not want to freeze the screen.
Here Is My Acivity
package thai.phrasi.ctech.com.phrasi;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Typeface;
import android.media.MediaPlayer;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.support.v7.app.ActionBarActivity;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.ViewFlipper;
import com.squareup.picasso.Picasso;
import org.json.JSONObject;
import java.lang.ref.WeakReference;
import java.util.ArrayList;
public class WordActivity extends ActionBarActivity {
categories category_obj;
word word_obj;
wordDB wordDb;
WordAdapter adapter;
MediaPlayer mPlayer;
boolean doubleBackToExitPressedOnce = false;
public static ViewFlipper viewFlipper;
public View view;
private static ProgressDialog pleaseWaitDialog;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_word);
viewFlipper = new ViewFlipper(this);
viewFlipper.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));
TextView txt = (TextView) findViewById(R.id.phraseListHeading);
Typeface font = Typeface.createFromAsset(WordActivity.this.getAssets(), "fonts/NotoSans-Regular.ttf");
String categoryName = getIntent().getExtras().getString("categoryName").toUpperCase();
wordDb = new wordDB(getApplicationContext());
getAllWords();
//asyncLoadWordList task2 = new asyncLoadWordList(getApplicationContext());
//task2.execute();
txt.setTypeface(font);
txt.setText(categoryName);
ListView wordListView;
wordListView = (ListView)findViewById(R.id.list_view_word);
wordListView.setOnItemClickListener(new AdapterView.OnItemClickListener(){
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Object o = parent.getItemAtPosition(position);
word_obj = (word) o;
if(Integer.valueOf(word_obj.getCategoryId())>=0) {
Intent myIntent = new Intent(WordActivity.this, WordDetailsActivity.class);
myIntent.putExtra("word_obj", word_obj);
myIntent.putExtra("position",position);
myIntent.putExtra("currentClickedId", word_obj.getCsvWordId().toString());
myIntent.putExtra("favouriteFlag",0);
myIntent.putExtra("searchFlag",0);
myIntent.putExtra("searchString", "");
WordActivity.this.startActivity(myIntent);
}
}
});
ImageView backButton = (ImageView) findViewById(R.id.backButton);
backButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent backIntent = new Intent(WordActivity.this, CategoryActivity.class);
View vw = FirstGroup.group.getLocalActivityManager().startActivity("CategoryActivity", backIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP)).getDecorView();
FirstGroup.group.replaceView(vw);
viewFlipper.removeAllViews();
System.runFinalization();
Runtime.getRuntime().gc();
System.gc();
}
});
}
#Override
protected void onPause() {
super.onPause(); // Don't forget this line
stop();
}
public void stop(){
mPlayer=adapter.getMPlayerInstace();
if(mPlayer!=null){
mPlayer.stop();
mPlayer.release();
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_word, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
protected void onResume(){
super.onResume();
new Thread(new Runnable() {
public void run(){
//All your heavy stuff here!!!
category_obj = (categories) getIntent().getSerializableExtra("category_obj");
if(viewFlipper.getChildCount() == 0) {
asyncFlipperView task = new asyncFlipperView(getApplicationContext());
task.execute(new String[]{category_obj.getCsvCategoryId().toString()});
}
}
}).start();
}
public void getAllWords(){
category_obj = (categories) getIntent().getSerializableExtra("category_obj");
ArrayList<word> words = new ArrayList<word>();
Cursor row = wordDb.selectWordList(category_obj.getCsvCategoryId().toString());
words.add(new word("-1", "-1", "", "", "", "", "", "", "x.mp3", ""));
words.add(new word("-2", "-2", "", "", "", "", "", "", "x.mp3", ""));
row.moveToFirst();
while (!row.isAfterLast()) {
//Log.d("Data id: ", row.getString(2));
words.add( new word(row.getString(0),row.getString(1),row.getString(2),row.getString(3),row.getString(4),row.getString(5), row.getString(6),row.getString(7),row.getString(8),row.getString(9)));
row.moveToNext();
}
row.close();
adapter = new WordAdapter(WordActivity.this, words);
ListView listView = (ListView) findViewById(R.id.list_view_word);
listView.setAdapter(adapter);
}
#Override
public void onBackPressed() {
if (doubleBackToExitPressedOnce) {
super.onBackPressed();
return;
}
this.doubleBackToExitPressedOnce = true;
//Toast.makeText(this, "Please click BACK again to exit", Toast.LENGTH_SHORT).show();
LayoutInflater inflater = getLayoutInflater();
View layout = inflater.inflate(R.layout.custom_toast, (ViewGroup) findViewById(R.id.toast_layout_root));
TextView text = (TextView) layout.findViewById(R.id.text);
text.setText("Double tap back button to exit.");
Toast toast = new Toast(getApplicationContext());
toast.setGravity(Gravity.CENTER_HORIZONTAL, 0, 0);
toast.setGravity(Gravity.CENTER_VERTICAL, 0, 0);
toast.setDuration(Toast.LENGTH_SHORT);
toast.setView(layout);
toast.show();
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
doubleBackToExitPressedOnce = false;
}
}, 2000);
}
public class asyncLoadWordList extends AsyncTask<ArrayList<word>, Void, ArrayList<word>>{
private Context mContext;
public asyncLoadWordList(Context context) {
mContext = context;
}
protected void onPreExecute() {
//Start the splash screen dialog
/* if (pleaseWaitDialog == null)
pleaseWaitDialog= ProgressDialog.show(WordActivity.this,
"PLEASE WAIT",
"Getting results...",
false);
*/
}
#Override
protected ArrayList<word> doInBackground(ArrayList<word>... params) {
wordDb = new wordDB(mContext);
category_obj = (categories) getIntent().getSerializableExtra("category_obj");
ArrayList<word> words = new ArrayList<word>();
Cursor row = wordDb.selectWordList(category_obj.getCsvCategoryId().toString());
words.add(new word("-1", "-1", "", "", "", "", "", "", "x.mp3", ""));
words.add(new word("-2", "-2", "", "", "", "", "", "", "x.mp3", ""));
row.moveToFirst();
while (!row.isAfterLast()) {
//Log.d("Data id: ", row.getString(2));
words.add( new word(row.getString(0),row.getString(1),row.getString(2),row.getString(3),row.getString(4),row.getString(5),row.getString(6),row.getString(7),row.getString(8),row.getString(9)));
row.moveToNext();
}
row.close();
return words;
}
protected void onPostExecute(ArrayList<word> result) {
adapter = new WordAdapter(WordActivity.this, result);
ListView listView = (ListView) findViewById(R.id.list_view_word);
listView.setAdapter(adapter);
if (pleaseWaitDialog != null) {
pleaseWaitDialog.dismiss();
pleaseWaitDialog = null;
}
asyncFlipperView task = new asyncFlipperView(getApplicationContext());
task.execute(new String[]{category_obj.getCsvCategoryId().toString()});
}
}
public class asyncFlipperView extends AsyncTask<String, Void, String[]> {
String categoryId;
private Context mContext;
wordDB wordDb;
Cursor row;
JSONObject json;
View view;
//private ProgressDialog dialog = new ProgressDialog(WordActivity.this);
public asyncFlipperView(Context context) {
mContext = context;
}
protected void onPreExecute() {
//Start the splash screen dialog
}
#Override
protected String[] doInBackground(String... params) {
categoryId = params[0];
json = new JSONObject();
/*do application level task*/
GlobalState state = ((GlobalState) mContext);
state.doAction();
/*Ends*/
wordDb = new wordDB(mContext);
row = wordDb.selectWordList(categoryId);
Log.d("Tag: search result", row.getString(2).toString());
return new String[]{categoryId};
}
protected void onPostExecute(String[] result) {
categoryId = result[0];
ImageView phraseImage = null;
Typeface font = Typeface.createFromAsset(WordActivity.this.getAssets(), "fonts/NotoSans-Regular.ttf");
row.moveToFirst();
while (!row.isAfterLast()) {
/*phrase Image*/
Integer fileNameLength = row.getString(5).toString().length();
String fileName = row.getString(5).toString();
String imageFile = fileName.substring(0, fileNameLength - 4);
//viewFlipper = (ViewFlipper)findViewById(R.id.flipper);
LayoutInflater inflater = getLayoutInflater();
view = inflater.inflate(R.layout.word_details_flipper_view, null);
TextView tv = (TextView) view.findViewById(R.id.text_english);
tv.setTypeface(font);
tv.setText(row.getString(2).toString());
String picName = row.getString(6).toString();
picName = picName.replace(".png", "");
Uri url1 = Uri.parse("android.resource://" + mContext.getPackageName() + "/drawable/" + picName);
ImageView backgroundImage = (ImageView) view.findViewById(R.id.backgroundImage);
Picasso.with(mContext).load(url1).fit().centerCrop().into(backgroundImage);
TextView tvTranslated = (TextView) view.findViewById(R.id.translated_phrase);
tvTranslated.setTypeface(font);
tvTranslated.setText(row.getString(3).toString());
TextView pronounce = (TextView) view.findViewById(R.id.pronounce);
pronounce.setTypeface(font);
pronounce.setText(row.getString(4).toString());
phraseImage = (ImageView) view.findViewById(R.id.phrase_image);
Uri url = Uri.parse("android.resource://" + mContext.getPackageName() + "/drawable/" + imageFile);
Picasso.with(mContext).load(url).resize(576, 888).into(phraseImage);
view.setTag(R.string.csvId, row.getString(0).toString());
viewFlipper.addView(view);
row.moveToNext();
}
row.close();
}
private Context getDialogContext() {
Context context;
if (getParent() != null) context = getParent();
else context = WordActivity.this;
return context;
}
}
}
In My Listview having 5 data,but Based On Km Distance Double Value ,sort the Full Listview in Ascending Order. All data fetching from Webservice. Showing Data In Listview Working But only Last Row Data Showing In Full List How to Resolve it Help me
package com.example;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import org.json.JSONArray;
import org.json.JSONObject;
import org.ksoap2.SoapEnvelope;
import org.ksoap2.serialization.PropertyInfo;
import org.ksoap2.serialization.SoapObject;
import org.ksoap2.serialization.SoapPrimitive;
import org.ksoap2.serialization.SoapSerializationEnvelope;
import org.ksoap2.transport.HttpTransportSE;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.app.ActivityOptions;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.location.Location;
import android.media.Rating;
import android.os.AsyncTask;
import android.os.Bundle;
import android.provider.Settings;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.RatingBar;
import android.widget.TextView;
import android.widget.Toast;
public class Find_Stores_1_Distance_Based_Tabview1 extends Fragment implements OnClickListener {
ListView listPage;
Button Near_Me, Top_Service, Rating_Based, Add_ServiceCenter;
View rootView;
int[] images = {
R.drawable.shop1,R.drawable.shop2,R.drawable.shop1,
R.drawable.shop1,R.drawable.shop2,R.drawable.shop1,
R.drawable.shop1,R.drawable.shop2,R.drawable.shop1}
Rating rateme;
float ratingValue = 2.0f;
String ServiceModel = " Phone ";
// for WebService Fetch from web to Find stores ..
private static final String SOAP_ACTION = "************";
private static final String NAMESPACE = "************";
private static final String URL = "************";
private static final String METHOD_NAME = "************";
private String TAG2 = "************";
public static String Status_Response_FindStores_Landing = "";
// for WebService Fetch from web to Find stores ..
private static final String SOAP_ACTION1 = ""************"";
private static final String NAMESPACE1 = ""************"";
private static final String URL1 = ""************"";
private static final String METHOD_NAME1 = ""************"";
private String TAG3 = ""************"";
public static String Status_Res_FindStores_Showpage_Data = "";
public String Center_id,Brand_name, ServiceCenterName,Address1,EMailId,ContactNumber,Pincode,Cityname,Latitude1,Longitude1;
public String Center_id2,Brand_name2, ServiceCenterName2,Address2,EMailId2,ContactNumber2,Pincode2,Cityname2;
// flag for Internet connection status
Boolean isInternetPresent = false;
// Connection detector class
InternetConnectionDetector cd1;
// Progress Bar
ProgressBar pg;
private ProgressDialog progress;
String[] SERVICE_CENTERNAME,Full_ADDRESS,CENTER_ID;
String[] KM_DISTANCE_StringArray;
TextView CenterIDText;
public String CategoryStringItem,BrandStringItem,CityStringItem;
public TextView NotfoundText1;
public Button ReloadButton1;
public String centerId_Service,LatitudeSingle_Service,LangitudeSingle_Service;
public String Latittude_LogitutdeString;
double latitude_Current, longitude_current;
// public Float distance;
public double distance1;
GPSTracker gps;
boolean _areLecturesLoaded = false;
//For Creating Double array;
String[] LatitudeArray,LangitudeArray;
public static int StatusoutPutInteger1;
//For Ascending Order Sort
private boolean mAscendingOrder[] = {true, true, true};
private ItemsListAdapter mAdapter;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
rootView = inflater.inflate(R.layout.find_stores_1_distancebased_tabview1,container, false);
// creating connection Detector class for checking Internet Status
cd1 = new InternetConnectionDetector(getActivity());
// create class object
gps = new GPSTracker(getActivity());
// call the views with this layout
listPage = (ListView) rootView.findViewById(R.id.listView123);
mAdapter = new ItemsListAdapter();
// ((ListView) rootView.findViewById(R.id.listView123)).setAdapter(mAdapter);
listPage.setAdapter(mAdapter);
// fillShoppingList();
return rootView;
}
public void onResume()
{
try {
super.onResume();
// get Internet status
isInternetPresent = cd1.isConnectingToInternet();
// check for Internet status
if (isInternetPresent)
{
// check if GPS enabled
if(gps.canGetLocation()){
latitude_Current = gps.getLatitude();
longitude_current = gps.getLongitude();
// for data Fetch from web
AsyncCallWSfor_PRODUCT task = new AsyncCallWSfor_PRODUCT();
// Call execute
task.execute();
}else{
// can't get location
// GPS or Network is not enabled
// Ask user to enable GPS/network in settings
gps.showSettingsAlert();
}
}
else
{
Toast.makeText(getActivity(),"Please Check Your Internet Connection ..!",Toast.LENGTH_SHORT).show();
}
} catch (Exception e)
{
e.printStackTrace();
Log.i("Exception in Tab1 Onresume","Error");
}
}
// for Product Web Sync
private class AsyncCallWSfor_PRODUCT extends AsyncTask<String, Void, Void> {
#Override
protected Void doInBackground(String... params)
{
Log.i(TAG2, "doInBackground");
try
{
getSignupdata1(CategoryStringItem,BrandStringItem,CityStringItem);
}
catch (Exception e)
{
// Toast.makeText(getActivity(),"error caught in do in background", Toast.LENGTH_SHORT).show();
Log.i(TAG2, "Error in Find Background");
e.printStackTrace();
}
return null;
// return null;
}
#Override
protected void onPostExecute(Void result)
{
//pg.setVisibility(View.INVISIBLE);
// To dismiss the dialog
progress.dismiss();
Log.i(TAG2, "onPostExecute");
try {
// Show items ascending
mAdapter.sortByPriceAsc();
listPage.setOnItemClickListener(new OnItemClickListener()
{
#Override public void onItemClick(AdapterView<?> arg0, View views,int position, long id)
{
try {
// get Internet status
isInternetPresent = cd1.isConnectingToInternet();
// check for Internet status
if (isInternetPresent)
// for Service Center Show page Data Fetch from web
AsyncCallWSfor_FETCHService_Center task = new AsyncCallWSfor_FETCHService_Center();
// Call execute
task.execute();
}
else
{
Toast.makeText(getActivity(),"Please Check Your Internet Connection..!",Toast.LENGTH_SHORT).show();
}
} catch (Exception e)
{
e.printStackTrace();
Log.i("Exception in Tab1 OnItemClick","Error");
}
}
});
}
} catch (Exception e) {
Log.i(TAG2, "Error in Product Insert");
//Toast.makeText(getActivity(), "Error in sucess",Toast.LENGTH_SHORT).show();
e.printStackTrace();
}
}
#Override
protected void onPreExecute()
{
progress.setTitle("Progress");
progress.setMessage("Please Wait Loading...");
progress.setProgressStyle(ProgressDialog.STYLE_SPINNER);
progress.setIndeterminate(true);
progress.show();
}
#Override
protected void onProgressUpdate(Void... values) {
Log.i(TAG2, "onProgressUpdate");
}
}
public void getSignupdata1(String Categoryitem,String Branditem, String CityLocation)
{
// Create request
SoapObject request = new SoapObject(NAMESPACE, METHOD_NAME);
PropertyInfo pi3 = new PropertyInfo();
pi3.setName("Categ");
pi3.setValue(Categoryitem);// get the string that is to be sent to the webservice
pi3.setType(String.class);
request.addProperty(pi3);
PropertyInfo pi4 = new PropertyInfo();
pi4.setName("Band");
pi4.setValue(Branditem);// get the string that is to be sent to the webservice
pi4.setType(String.class);
request.addProperty(pi4);
PropertyInfo pi5= new PropertyInfo();
pi5.setName("City");
pi5.setValue(CityLocation);// get the string that is to be sent to the webservice
pi5.setType(String.class);
request.addProperty(pi5);
// Create envelope
SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
envelope.dotNet = true;
// Set output SOAP object
envelope.setOutputSoapObject(request);
// Create HTTP call object
HttpTransportSE androidHttpTransport = new HttpTransportSE(URL);
try {
// Invole web service
androidHttpTransport.call(SOAP_ACTION, envelope);
// Get the response
SoapPrimitive response = (SoapPrimitive) envelope.getResponse();
if ((response.toString()).contains("{"))
{
// JSONArray jr = new JSONArray(response);
SoapObject rep = (SoapObject) envelope.bodyIn;
JSONArray jr = new JSONArray(rep.getPropertyAsString(0));
for (int i = 0; i < jr.length(); i++)
{
JSONObject jb = (JSONObject) jr.get(i);
Center_id = jb.getString("CenterId");
Brand_name = jb.getString("Brand");
ServiceCenterName = jb.getString("Center");
Address1 = jb.getString("Add");
EMailId = jb.getString("mail");
ContactNumber = jb.getString("Contact");
Pincode = jb.getString("PinCode");
Cityname = jb.getString("City");
Latitude1=jb.getString("latitude");
Longitude1=jb.getString("longitude");
double latitude_Doublevalue = Double.parseDouble(Latitude1);
double longitude_Doublevalue = Double.parseDouble(Longitude1);
try
{
Location locationA = new Location("point A");
locationA.setLatitude(latitude_Current);
locationA.setLongitude(longitude_current);
Location locationB = new Location("point B");
locationB.setLatitude(latitude_Doublevalue);
locationB.setLongitude(longitude_Doublevalue);
// distance = locationA.distanceTo(locationB)/1000;//Distance in Kilometers
distance1 = locationA.distanceTo(locationB)/1000;
Log.i("Service_CenterNameStringOutput","Out "+ServiceCenterName);
Log.i("AddressStringOutput","Out "+Address1);
Log.i("DistanceStringOutput","Out "+distance1);
}
catch(Exception ex)
{
ex.printStackTrace();
Log.i(TAG2, "Error in Distance Calculate");
}
getActivity().runOnUiThread(new Runnable() {
#Override
public void run() {
fillShoppingList(Address1,ServiceCenterName,distance1);
}
});
// Log.i("CenterIdssss", Center_id);
}
}
else
{
Status_Response_FindStores_Landing = response.toString();
}
} catch (Exception e) {
Log.i(TAG2, "Error in Signup1 catch");
e.printStackTrace();
}
}
//GPS Enabler
public void showSettingsAlert() {
AlertDialog.Builder alertDialog = new AlertDialog.Builder(
getActivity());
alertDialog.setTitle("Settings");
alertDialog.setMessage("Enable Location Provider! Go to settings menu?");
alertDialog.setPositiveButton("Settings",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
Intent intent = new Intent(
Settings.ACTION_LOCATION_SOURCE_SETTINGS);
getActivity().startActivity(intent);
}
});
alertDialog.setNegativeButton("Cancel",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
alertDialog.show();
}
private void fillShoppingList(String address12, String serviceCenterName3, double distance12string )
{
SortAscendingClass item = new SortAscendingClass();
item.setAddressArray(address12);
item.setCmpy_NameArray(serviceCenterName3);
item.setDistancekmArray(distance12string);
mAdapter.addItem(item);
//mAdapter.sortByPriceAsc();
}
/** Adapter for the shopping list items */
private class ItemsListAdapter extends BaseAdapter {
private LayoutInflater vi;
private ArrayList<SortAscendingClass> shoppingList = new ArrayList<SortAscendingClass>();
public ItemsListAdapter()
{
vi = (LayoutInflater)getActivity().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
/** Add white line */
public void addItem(SortAscendingClass item) {
shoppingList.add(item);
notifyDataSetChanged();
}
/** Sort shopping list by price ascending */
public void sortByPriceAsc() {
Comparator<SortAscendingClass> comparator = new Comparator<SortAscendingClass>() {
#Override
public int compare(SortAscendingClass object1, SortAscendingClass object2) {
return Double.compare(object1.getDistancekmArray(), object2.getDistancekmArray());
}
};
Collections.sort(shoppingList, comparator);
notifyDataSetChanged();
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder = null;
if (convertView == null) {
holder = new ViewHolder();
convertView = vi.inflate(R.layout.findstores_service_center_tabview1_2_3_listview, null);
holder.myImage = (ImageView) convertView.findViewById(R.id.imageView1);
holder.ServcieCenterFullname = (TextView) convertView.findViewById(R.id.textView1);
holder.AddressName = (TextView) convertView.findViewById(R.id.textView2);
holder.ratingtext = (RatingBar)convertView.findViewById(R.id.ratingBarinTabs);
holder.myDistance = (TextView) convertView.findViewById(R.id.Distance);
holder.SErvice_Available = (TextView) convertView.findViewById(R.id.serviceCategory);
/*holder.CenterIDText=(TextView)convertView.findViewById(R.id.CenterId_xml);
holder.LatitudeText=(TextView)convertView.findViewById(R.id.latitude_xml);
holder.LangitudeText=(TextView)convertView.findViewById(R.id.langitude_xml);*/
convertView.setTag(holder);
}
else {
holder = (ViewHolder) convertView.getTag();
}
holder.myImage.setImageResource(images[position]);
holder.ServcieCenterFullname.setText(String.valueOf(shoppingList.get(position).getCmpy_NameArray()));
holder.AddressName.setText(String.valueOf(shoppingList.get(position).getAddressArray()));
holder.ratingtext.setRating(ratingValue); // to set rating value
holder.myDistance.setText(String.valueOf(shoppingList.get(position).getDistancekmArray()+" Km"));
holder.SErvice_Available.setText(ServiceModel);
return convertView;
}
#Override
public int getCount() {
return shoppingList.size();
}
#Override
public Object getItem(int position) {
return shoppingList.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
/** Helper class acting as a holder of the information for each row */
private class ViewHolder {
/*public TextView name;
public TextView price;
public TextView quantity;*/
public ImageView myImage;
public TextView ServcieCenterFullname;
public TextView AddressName ;
public RatingBar ratingtext ;
public TextView myDistance;
public TextView SErvice_Available;
public TextView CenterIDText;
public TextView LatitudeText;
public TextView LangitudeText;
}
}
}
You can use Collections and ArrayList also to sort out as per below.
Collections.sort(YourArrayList);
You can sort your adapter backing the ListView by that listview will automatically sort.
Use an ArrayAdapter, order the elements inside the array asociated whit the adapter by your integer and link the adapter to your listView.
Hi i have this android project where after searching for an Author in the app and the results is clicked i get an empty view instead of the Author displaying his or her quotes
This is the code am using...Thanks
package com.dennisboga.successquotes;
import java.util.ArrayList;
import java.util.HashMap;
import com.google.android.gms.ads.AdRequest;
import com.google.android.gms.ads.AdView;
import android.widget.AdapterView.OnItemClickListener;
import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.database.Cursor;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ListView;
public class AuthorsActivity extends Activity {
ListView list;
LazyAuthorsAdapter adapter;
LazyAuthorsAdapter adapterSort;
DAO db;
Cursor cu;
static final String KEY_ID = "_auid";
static final String KEY_NAME = "au_name";
static final String KEY_PICTURE = "au_picture";
static final String KEY_PICTURE_SDCARD = "au_picture_sdcard";
static final String KEY_WEB_ID = "au_web_id";
static final String KEY_COUNT = "count";
static final String KEY_QUOTES_NUM = "quotes_num";
ImageButton search;
EditText inputSearch;
int textlength = 0;
ArrayList<HashMap<String, String>> authorsList;
ArrayList<HashMap<String, String>> authorsListSort = new ArrayList<HashMap<String, String>>();;
HashMap<String, String> map;
// ============================================================================= =
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
db = new DAO(this);
db.open();
//addAuthors();
//addQuotes();
Cursor c = db.getAllAuthors();
if (c.getCount() != 0) {
setContentView(R.layout.activity_authors);
authorsList = new ArrayList<HashMap<String, String>>();
do {
map = new HashMap<String, String>();
// adding each child node to HashMap key => value
map.put(KEY_ID, c.getString(c.getColumnIndex(KEY_ID)));
map.put(KEY_NAME, c.getString(c.getColumnIndex(KEY_NAME)));
map.put(KEY_PICTURE, c.getString(c.getColumnIndex(KEY_PICTURE)));
map.put(KEY_PICTURE_SDCARD, String.valueOf(c.getInt(c
.getColumnIndex(KEY_PICTURE_SDCARD))));
map.put(KEY_WEB_ID,
String.valueOf(c.getInt(c.getColumnIndex(KEY_WEB_ID))));
map.put(KEY_QUOTES_NUM,
c.getString(c.getColumnIndex(KEY_COUNT)));
// adding HashList to ArrayList
authorsList.add(map);
} while (c.moveToNext());
list = (ListView) findViewById(R.id.list);
// Getting adapter by passing xml data ArrayList
adapter = new LazyAuthorsAdapter(this, authorsList);
list.setAdapter(adapter);
// Click event for single list row
list.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
if (authorsListSort.size() != 0) {
map = authorsListSort.get(position);
} else {
map = authorsList.get(position);
}
Intent intent = new Intent(AuthorsActivity.this,
QuotesActivity.class);
intent.putExtra("AuthorId", map.get(KEY_WEB_ID));
intent.putExtra("quotesType", 3);
startActivity(intent);
}
});
search = (ImageButton) findViewById(R.id.search);
inputSearch = (EditText) findViewById(R.id.inputSearch);
search.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
if (inputSearch.getVisibility() == View.GONE) {
inputSearch.setVisibility(View.VISIBLE);
} else {
inputSearch.setText("");
inputSearch.setVisibility(View.GONE);
}
}
});
inputSearch = (EditText) findViewById(R.id.inputSearch);
inputSearch.addTextChangedListener(new TextWatcher() {
public void afterTextChanged(Editable s) {
}
public void beforeTextChanged(CharSequence s, int start,
int count, int after) {
}
public void onTextChanged(CharSequence s, int start,
int before, int count) {
authorsListSort.clear();
for (int i = 0; i < authorsList.size(); i++) {
map = authorsList.get(i);
String auID = map.get(KEY_ID);
String auName = map.get(KEY_NAME);
String auPicture = map.get(KEY_PICTURE);
String auPictureSDCard = map.get(KEY_PICTURE_SDCARD);
String auQuotesNum = map.get(KEY_QUOTES_NUM);
if (auName.toLowerCase().startsWith(
s.toString().toLowerCase())
|| auName.toLowerCase().contains(
" " + s.toString().toLowerCase())) {
map = new HashMap<String, String>();
// adding each child node to HashMap key =>
// value
map.put(KEY_ID, auID);
map.put(KEY_NAME, auName);
map.put(KEY_PICTURE, auPicture);
map.put(KEY_PICTURE_SDCARD, auPictureSDCard);
map.put(KEY_QUOTES_NUM, auQuotesNum);
// adding HashList to ArrayList
authorsListSort.add(map);
}
}
// }
adapterSort = new LazyAuthorsAdapter(AuthorsActivity.this,
authorsListSort);
list.setAdapter(adapterSort);
}
});
} else {
}
AdView ad = (AdView) findViewById(R.id.adView);
ad.loadAd(new AdRequest.Builder().build());
}
// ============================================================================= =
#Override
protected void onResume() {
db.open();
super.onResume();
}
// ============================================================================= =
#Override
protected void onRestart() {
// TODO Auto-generated method stub
Intent intent = getIntent();
intent.setFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION);
finish();
startActivity(intent);
super.onRestart();
}
// ============================================================================= =
#Override
protected void onPause() {
db.closeDatabase();
super.onPause();
}
// private void addAuthors() {
// cu = db.getAuthors2();
//
// if (cu.getCount() != 0) {
//
// do {
// db.addAuthors2(cu.getString(cu.getColumnIndex("au_name")),
// cu.getInt(cu.getColumnIndex("_auid")));
//
// } while (cu.moveToNext());
// }
// }
//
// ============================================================================= =
// private void addQuotes() {
// cu = db.getQuotes2();
//
// if (cu.getCount() != 0) {
//
// do {
// db.addQuotes2(cu.getString(cu.getColumnIndex("qu_text")),
// cu.getInt(cu.getColumnIndex("qu_author")),
// cu.getInt(cu.getColumnIndex("_quid")));
//
// } while (cu.moveToNext());
// }
// }
}
quotesactivity
package com.dennisboga.successquotes;
import java.util.ArrayList;
import java.util.HashMap;
import com.google.android.gms.ads.AdRequest;
import com.google.android.gms.ads.AdView;
import android.widget.AdapterView.OnItemClickListener;
import android.os.Bundle;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ImageButton;
import android.widget.ListView;
public class QuotesActivity extends Activity {
ListView list;
LazyQuotesAdapter adapter;
AlertDialog PageDialog;
DAO db;
Cursor c;
static final String KEY_ID = "_quid";
static final String KEY_TEXT = "qu_text";
static final String KEY_AUTHOR = "au_name";
static final String KEY_PICTURE = "au_picture";
static final String KEY_PICTURE_SDCARD = "au_picture_sdcard";
static final String KEY_WEB_ID = "au_web_id";
static final String KEY_FAVORITE = "qu_favorite";
ArrayList<HashMap<String, String>> quotesList;
HashMap<String, String> map;
ArrayList<HashMap<String, String>> pages;
Integer quType;
ImageButton page;
int itemSelected;
// ==============================================================================
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
db = new DAO(this);
db.open();
setContentView(R.layout.activity_quotes);
AdView ad = (AdView) findViewById(R.id.adView);
ad.loadAd(new AdRequest.Builder().build());
quType = getIntent().getIntExtra("quotesType", 0);
page = (ImageButton) findViewById(R.id.pager);
if (quType != 0) {
switch (quType) {
case 1:
if (getIntent().getStringExtra("startFrom") == null) {
c = db.getQuotes("0");
} else {
c = db.getQuotes(getIntent().getStringExtra("startFrom"));
}
break;
case 2:
c = db.getFavoriteQuotes();
page.setVisibility(View.GONE);
break;
case 3:
c = db.getAuthorQuotes(getIntent().getStringExtra("AuthorId"));
page.setVisibility(View.GONE);
break;
}
}
if (c.getCount() != 0) {
if (getIntent().getStringExtra("startLabel") != null) {
page = (ImageButton) findViewById(R.id.pager);
}
quotesList = new ArrayList<HashMap<String, String>>();
list = (ListView) findViewById(R.id.list);
do {
map = new HashMap<String, String>();
// adding each child node to HashMap key => value
map.put(KEY_ID, c.getString(c.getColumnIndex(KEY_ID)));
map.put(KEY_TEXT, c.getString(c.getColumnIndex(KEY_TEXT)));
map.put(KEY_AUTHOR, c.getString(c.getColumnIndex(KEY_AUTHOR)));
map.put(KEY_PICTURE, c.getString(c.getColumnIndex(KEY_PICTURE)));
map.put(KEY_PICTURE_SDCARD, String.valueOf(c.getInt(c
.getColumnIndex(KEY_PICTURE_SDCARD))));
map.put(KEY_WEB_ID,
String.valueOf(c.getInt(c.getColumnIndex(KEY_WEB_ID))));
// adding HashList to ArrayList
quotesList.add(map);
} while (c.moveToNext());
// Getting adapter by passing xml data ArrayList
adapter = new LazyQuotesAdapter(this, quotesList);
list.setAdapter(adapter);
// Click event for single list row
list.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
map = quotesList.get(position);
Intent intent = new Intent(QuotesActivity.this,
QuoteDialogActivity.class);
intent.putExtra("QuoteId", map.get(KEY_ID));
intent.putExtra("quotesType", quType);
startActivity(intent);
}
});
page.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// Strings to Show In Dialog with Radio Buttons
final CharSequence[] items = { "01 - 50", "51 - 100",
"101 - 150", "151 - 200", "201 - 250", "251 - 300",
"301 - 350", "351 - 400", "401 - 450", "451 - 500",
"501 - 550", "551 - 600", "601 - 650", "651 - 700",
"701 - 750", "751 - 800", "801 - 850", "851 - 900",
"901 - 950", "951 - 1000", "1001 - ..." };
pages = new ArrayList<HashMap<String, String>>();
for (int i = 0; i <= 1000; i += 50) {
HashMap<String, String> pageMap = new HashMap<String, String>();
pageMap.put("start", String.valueOf(i));
pages.add(pageMap);
}
// Creating and Building the Dialog
AlertDialog.Builder builder = new AlertDialog.Builder(
QuotesActivity.this);
builder.setTitle("Display Quotes");
itemSelected = getIntent().getIntExtra("itemSelected", 0);
builder.setSingleChoiceItems(items, itemSelected,
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,
int item) {
Intent intent = getIntent();
intent.putExtra("startFrom", pages
.get(item).get("start"));
intent.putExtra("startLabel", items[item]);
intent.putExtra("itemSelected", item);
intent.setFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION);
finish();
startActivity(intent);
}
});
builder.setNegativeButton("Dismiss",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,
int id) {
// action on dialog close
}
});
PageDialog = builder.create();
PageDialog.show();
}
});
} else {
}
}
// ============================================================================= =
#Override
protected void onResume() {
db.open();
super.onResume();
}
// ============================================================================= =
#Override
protected void onPause() {
db.closeDatabase();
super.onPause();
}
}
//testselect.java
package com.example.eleave;
import java.util.ArrayList;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.util.SparseBooleanArray;
import android.view.View;
import android.widget.Button;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
public class TestSelect extends Activity {
Intent i;
Button btn4;
CharSequence[] options;
protected ArrayList<CharSequence> selectedSubjects = new ArrayList<CharSequence>();
boolean[] selections;
String s1;
String sub[]=new String[5];
TextView tv2;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.testselect);
i=getIntent();
s1=i.getStringExtra("data1");
tv2=(TextView) findViewById(R.id.textView2);
btn4=(Button) findViewById(R.id.button4);
btn4.setOnClickListener(new ButtonClickHandler());
Bundle bundle = getIntent().getExtras();
String username = bundle.getString("username");
String reason = bundle.getString("reason");
String sem = bundle.getString("sem");
String from = bundle.getString("from");
String to = bundle.getString("to");
AsyncTask<String,Void,String> t1=new LeaveTask(TestSelect.this).execute(username,sem,reason,from,to);
try{
String result=t1.get();
Toast.makeText(getBaseContext(), result,Toast.LENGTH_LONG).show();
}catch(Exception e)
{
}
}
public class ButtonClickHandler implements View.OnClickListener {
public void onClick( View view ) {
if(s1.equals("III"))
{
options=new CharSequence[]{"DSPD","CAO","BDP"};
selections = new boolean[ options.length ];
}
else if(s1.equals("IV"))
{
options=new CharSequence[] {"TOFCS","OOP","OS"};
selections = new boolean[ options.length ];
}
else if(s1.equals("V"))
{
options=new CharSequence[] {"MI","CG","SP"};
selections = new boolean[ options.length ];
}
else
{
options=new CharSequence[] {"DAA","DBMS","ICWS"};
selections = new boolean[ options.length ];
}
showDialog( 0 );
/* do whatever you want with the checked item */
}
}
#Override
protected Dialog onCreateDialog( int id )
{
return
new AlertDialog.Builder( this )
.setTitle( "SUBJECTS" )
.setMultiChoiceItems( options, selections, new DialogSelectionClickHandler() )
.setPositiveButton( "OK", new DialogButtonClickHandler() )
.create();
}
public class DialogSelectionClickHandler implements DialogInterface.OnMultiChoiceClickListener
{
public void onClick( DialogInterface dialog, int clicked, boolean selected )
{
Log.i( "ME", options[ clicked ] + " selected: " + selected );
if(selected)
{
selectedSubjects.add(options[clicked]);
}
else
{
selectedSubjects.remove(options[clicked]);
}
}
}
public class DialogButtonClickHandler implements DialogInterface.OnClickListener
{
private final String NULL = null;
boolean[] checkedSubjects = new boolean[options.length];
int count = options.length;
public void onClick( DialogInterface dialog, int clicked, boolean isChecked)
{
switch( clicked )
{
case DialogInterface.BUTTON_POSITIVE:
printSelectedSubjects();
break;
}
}
private void printSelectedSubjects() {
// TODO Auto-generated method stub
for( int i = 0; i < options.length; i++ ){
Log.i( "ME", options[ i ] + " selected: " + selections[i] );
}
for(int i = 0; i < count; i++)
checkedSubjects[i] = selectedSubjects.contains(options[i]);
StringBuilder stringBuilder = new StringBuilder();
for(CharSequence subject : selectedSubjects)
stringBuilder.append(subject + ",");
tv2=(TextView) findViewById(R.id.textView2);
tv2.setText(stringBuilder.toString());
}
#Override
public void onClick(DialogInterface arg0, int arg1) {
// TODO Auto-generated method stub
}
}
}
I am passing value of s1 that is semester from some other activity and each semester has set of subjects I need to select more than one subject and extract all the values as string but I am unable to do so.Please help
I advise you to look at this code sample: here
The sample is actually quite similar to what you are trying to do...
You don't need to keep track of the checked items yourself. You can just use the boolean-array you passed to the dialog. "selections" in your case.