Java/Android scoop - java

Why does Log.d("Test", "" + ListOfAttractions3.size() + ""); Return 0 when Log.d("Test2", "" + ListOfAttractions3.size() + ""); returns 2 even thoughDatabseRequest(); is called first? Some how Log 2 is also printed last but I can't see why?
Code:
public class Testlist extends Activity {
List<Attractions> ListOfAttractions3 = new ArrayList<>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_testlist);
DatabseRequest();
Log.d("Test", "" + ListOfAttractions3.size() + "");
}
/*private void reFreshDisplay(){
ListView listView2 = (ListView) findViewById(R.id.listView2);
ArrayAdapter<Attractions> adapter = new ArrayAdapter<Attractions>(this, android.R.layout.simple_list_item_1, ListOfAttractions3);
listView2.setAdapter(adapter);
adapter.notifyDataSetChanged();
}*/
private void DatabseRequest(){
Response.Listener<String> responseListener = new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONArray jsonArray = new JSONArray(response);
int i = 0;
while(i < jsonArray.length()) {
JSONObject jsonObject = jsonArray.getJSONObject(i);
boolean success;
if (jsonObject.getBoolean("success")) success = true;
else success = false;
if (success) {
String attractionname = jsonObject.getString("attractionname");
double lng = jsonObject.getDouble("longitude");
double lat = jsonObject.getDouble("latitude");
int Rating = jsonObject.getInt("rating");
Attractions attraction = new Attractions(attractionname, lng, lat, Rating);
ListOfAttractions3.add(attraction);
Log.d("Test2", "" + ListOfAttractions3.size() + "");
} else {
AlertDialog.Builder builder = new AlertDialog.Builder(Testlist.this);
builder.setMessage("Connection to server Failed")
.setNegativeButton("Retry", null)
.create()
.show();
}
i++;
}
} catch (JSONException e) {
e.printStackTrace();
}
}
};
AttractionRequest attractionRequest = new AttractionRequest(responseListener);
RequestQueue queue2 = Volley.newRequestQueue(Testlist.this);
queue2.add(attractionRequest);
}
}

Related

Android Spinner does not work

i'm doing a spinner that retrieves its items from an API, i checked Postman results but there's no error there and somehow i cant even click the spinner or the spinner just doesnt drop down, here's the codes, i checked all other solutions already but not quite like this
Spinner xml:
<Spinner
android:id="#+id/select_plan_spinner"
android:layout_width="match_parent"
android:layout_height="50dp"
android:layout_marginLeft="10dp"
android:layout_weight="1"
android:background="#drawable/sos_edit_bg"
android:gravity="center"
android:spinnerMode="dropdown"
android:textColor="#color/white_new"
android:visibility="visible"></Spinner>
Spinner:
plan_spinner = (Spinner) findViewById(R.id.select_plan_spinner);
plan_spinner:
plan_spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
plan_id = PLAN_ID.get(position);
Double price = PLAN_PRICE.get(position);
planprice = price;
Log.e("planprice", "planprice>>" + planprice);
if (plan_id != 0) {
int pos = position - 1;
String view_route = feeditem.get(pos).getIMEI();
if (view_route.equals("0")) {
view_route = "No";
} else {
view_route = "yes";
}
desc.setText("Description: " +
feeditem.get(pos).getMessage() + "\n View Route History: " + view_route);
} else {
desc.setText("Please select plan");
}
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
API:
private void Get_plan_list() {
// TODO Auto-generated method stub
pDialog = new ProgressDialog(Select_plan.this);
pDialog.setMessage("Please wait...");
pDialog.setCancelable(false);
pDialog.show();
StringRequest req = new StringRequest(Request.Method.POST, Config.YOUR_API_URL + "planlist",
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
pDialog.dismiss();
// response
Log.e("Responsesearch", response);
try {
JSONObject obj = new JSONObject(response);
int success = obj.getInt("success");
if (success == 1) {
JSONArray array = obj.getJSONArray("planlist");
for (int i = 0; i < array.length(); i++) {
JSONObject jsobj = array.getJSONObject(i);
int p_id = jsobj.getInt("plan_id");
plan_name = jsobj.getString("plan_name");
planprice = jsobj.getDouble("plan_price");
timeperoide = jsobj.getString("view_route");
allow_devices = jsobj.getString("allowed_device");
description = jsobj.getString("description");
UserData detail = new UserData();
detail.setID(p_id);
detail.setName(plan_name);
detail.setEmail(allow_devices);
detail.setMessage(description);
detail.setIMEI(timeperoide);
detail.setMobile(String.valueOf(planprice));
feeditem.add(detail);
PLAN_ID.add(p_id);
PLAN_PRICE.add(planprice);
PLAN_NAME.add(plan_name + "( USD " + planprice + ")");
ArrayAdapter<String> data2 = new ArrayAdapter<String>(Select_plan.this,
R.layout.spinner_item, PLAN_NAME);
plan_spinner.setAdapter(data2);
// for auto set spinner Value
Log.e("plan_id_intent", "plan_id_intent>>" + plan_id_intent);
if (plan_id_intent == null) {
} else {
int position = Integer.parseInt(plan_id_intent);
int index = PLAN_ID.indexOf(position);
plan_spinner.setSelection(index);
}
}
} else if (success == 0) {
String msg = obj.getString("text");
Toast.makeText(getApplicationContext(), "" + msg, Toast.LENGTH_LONG).show();
} else if (success == 2) {
}
} catch (JSONException e) {
// TODO Auto-generated catch block
Log.e("Error.Response", e.toString());
e.printStackTrace();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
pDialog.dismiss();
// error
Log.e("Error.Response", error.toString());
}
}
) {
#Override
protected Map<String, String> getParams() {
Map<String, String> params = new HashMap<String, String>();
return params;
}
};
// for response time increase
req.setRetryPolicy(new DefaultRetryPolicy(DefaultRetryPolicy.DEFAULT_TIMEOUT_MS * 2,
DefaultRetryPolicy.DEFAULT_MAX_RETRIES, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
req.setShouldCache(false);
AppController.getInstance().addToRequestQueue(req);
}

Empty ArrayList Inside onResponse

I am developing an app for Downloading Images and their Description from Flickr.
I am setting Description String into GetterAndSetter Class's ArrayList and when i want to fetch the Data from that class,
even logger not Printing. And so that when i tried to set the values from stringArray onto the UI, I am getting ArrayIndexoutofBound Exception.
My Code is Following :
#Override
protected void onCreate(Bundle savedInstanceState) {
...
LoadImages(this);
...
}
My LoadImages Method :
private void LoadImages(MainActivity mainActivity) {
if (checkInternet()) {
StringRequest stringRequest = new StringRequest(URL, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.d("Respone", "onResponse: " + response);
// Used to Get List of Images URLs
getResponse = ParseJSON(response);
List<String> urlList = getResponse.get(0);
List<String> titles = getResponse.get(1);
// Getting String Array from GetterAndSetter Class...
// Not Properly Getting from there...
List<String> Details = getterAndSetter.getStringList();
// Printing Check
for (String urls:urlList) {
Log.d("urls", urls);
}
// Printing Check
for (String title:titles) {
Log.d("titles", title);
}
// Problem is here, Not Getting
**This is not even Executing...**
for (String str: Details) {
Log.d("GetDetails", str);
}
...
}
}, error -> {
Log.d(TAG, "onErrorResponse: Error Occured...");
});
RequestQueue requestQueue = Volley.newRequestQueue(this);
requestQueue.add(stringRequest);
mView.show(getSupportFragmentManager(), "Loading...");
} else {
Toast.makeText(this, "Turn Internet on...", Toast.LENGTH_SHORT).show();
}
}
My ParseJSON method :
ArrayList<ArrayList<String>> ParseJSON(String URL) {
try {
...
ArrayList<String> listURLS = new ArrayList<>();
ArrayList<String> Titles = new ArrayList<>();
ArrayList<ArrayList<String>> result = new ArrayList<>();
for (int i = 0; i < photo.length(); i++) {
JSONObject photosJSONObject = photo.getJSONObject(i);
String FarmID = photosJSONObject.getString("farm");
String ServerID = photosJSONObject.getString("server");
String ID = photosJSONObject.getString("id");
String SecretID = photosJSONObject.getString("secret");
String ImageTitle = photosJSONObject.getString("title");
listURLS.add(i, CreatePhotoURL(FarmID, ServerID, ID, SecretID));
Titles.add(i, ImageTitle);
String CreateURL = "https://api.flickr.com/services/rest/?method=flickr.photos.getInfo&api_key=" + API_Key + "&photo_id=" + ID + "&format=json&nojsoncallback=1";
AddtoList(CreateURL);
result.add(listURLS);
result.add(Titles);
}
return result;
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
My AddtoList Method :
public void AddtoList(String CreateURL) {
RequestQueue requestQueue = Volley.newRequestQueue(this);
StringRequest stringRequest = new StringRequest(CreateURL, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.d("Desc", response);
JSONObject root = null;
try {
root = new JSONObject(response);
JSONObject photo = root.getJSONObject("photo");
String username = photo.getJSONObject("owner").getString("username");
String DateTaken = photo.getJSONObject("dates").getString("taken");
String Views = photo.getString("views");
String FormattedStr = "Date Taken : " + DateTaken + "\n" + "Views : " + Views + "\n" + "User Name : " + username + "\n";
// Properly Working...
Log.d("Describe", FormattedStr);
// I cant say about this...
getterAndSetter.getStringList().add(FormattedStr);
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.d(TAG, "onErrorResponse: " + error.toString());
}
});
requestQueue.add(stringRequest);
}
My GetterAndSetter Class :
public final class GetterAndSetter {
private final ArrayList<String> stringList = new ArrayList<>();
public ArrayList<String> getStringList() {
return stringList;
}}

ArrayList.size function doesnt reflect changes of first try but if i run the method again solves that

I have a array list that takes changes on a AsyncTask that is called on a button click, after that i want to loop through the arraylist
for (int f = 0; f < getid.size();f++){
teste[f] = getid.get(f);
Log.d("teste", "welelelelelele ?");
}
but it cant because getid.size returns 0 so it doesnt execute(only on the first time i clicked the button), but why ? If i press back then click the button again it works, it returns the correct size and executes the for cycle.
ButtonClick
btnCriar.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
SparseBooleanArray checked = listView.getCheckedItemPositions();
ArrayList<String> selectedItems = new ArrayList<String>();
for (int i = 0; i < checked.size(); i++) {
// Item position in adapter
int position = checked.keyAt(i);
// Add sport if it is checked i.e.) == TRUE!
if (checked.valueAt(i))
selectedItems.add((String) adapter.getItem(position));
}
final String[] outputStrArr = new String[selectedItems.size()];
for (int i = 0; i < selectedItems.size(); i++) {
outputStrArr[i] = selectedItems.get(i);
Log.d("teste", String.valueOf(i));
}
Log.e("teste", "chega aqui ?===??");
new Get(outputStrArr).execute();
Log.e("teste", String.valueOf(getid.size()));
String[] teste = new String[getid.size()];
Log.e("teste", "chega aqui ?===??");
for (int f = 0; f < getid.size();f++){
teste[f] = getid.get(f);
Log.d("teste", "welelelelelele ?");
}
for (int va = 0; va < teste.length;va++){
Log.d("teste", "adadada ?");
pls +=teste[va];
}
editText.setText(pls);
Intent x = new Intent(AddCenario.this, GerirCenario.class);
Bundle b = new Bundle();
b.putStringArray("selectedItems", outputStrArr);
String text = editText.getText().toString();
x.putExtra("ola" , text);
x.putExtras(b);
startActivity(x);
listView.getSelectedItem();
}
});
Asynctask:
private class Get extends AsyncTask<String, Void, Void> {
private final String[] outputStrArr;
Get(String[] outputStrArr)
{
this.outputStrArr = outputStrArr;
}
#Override
protected void onPreExecute() {
}
#Override
protected Void doInBackground(String... integers) {
for (x = 0; x < outputStrArr.length; x++) {
try {
RequestQueue queue = Volley.newRequestQueue(AddCenario.this);
String url = "http://brunos.000webhostapp.com/teste/obter_id.php?descricao=" + outputStrArr[x];
JsonArrayRequest jsonRequest = new JsonArrayRequest
(Request.Method.GET, url, null, new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
try {
for (int i = 0; i < response.length(); ++i) {
JSONObject obj = response.getJSONObject(i);
id[0] = obj.getString("id");
getid.add(id[0]);
Log.d("teste", "chega aqui ?");
Log.e("teste", String.valueOf(getid.size()));
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
error.printStackTrace();
}
});
queue.add(jsonRequest);
} catch (Exception ex) {
}
}
return null;
}
protected void onPostExecute(Void result) {
super.onPostExecute(result);
}
}
Complete code:
public class AddCenario extends AppCompatActivity {
String input,pls, kappa;
Integer podeIR = 0,x;
EditText editText,esc;
String idDivisao;
private String my_sel_items;
ArrayAdapter adapter;
String[] id = new String[1];
ArrayList<String> getid = new ArrayList<String>();
#Override
protected void onCreate(Bundle savedInstanceState) {
final ArrayList<String> divisoes = new ArrayList<>();
my_sel_items=new String();
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_add_cenario);
editText = (EditText) findViewById(R.id.editText4);
final ListView listView = (ListView) findViewById(R.id.listview);
Button btnCriar = (Button) findViewById(R.id.button_criarr);
RequestQueue queue = Volley.newRequestQueue(AddCenario.this.getApplicationContext());
try {
String url = "http://brunos.000webhostapp.com/teste/listar_divisoes.php";
JsonArrayRequest jsonRequest = new JsonArrayRequest
(Request.Method.GET, url, null, new Response.Listener<JSONArray>() {
public void onResponse(JSONArray response) {
try {
adapter = new ArrayAdapter(getApplicationContext(),R.layout.custom_divi_mult,divisoes);
Integer i = 0;
String divisao;
while (i!= response.length()){
JSONObject obj = response.getJSONObject(i);
idDivisao = obj.getString("id");
divisao = obj.getString("descricao");
divisoes.add(divisao);i++;
}
listView.setAdapter(adapter);
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
error.printStackTrace();
}
});
queue.add(jsonRequest);
} catch (Exception ex) {
} finally {
}
btnCriar.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
SparseBooleanArray checked = listView.getCheckedItemPositions();
ArrayList<String> selectedItems = new ArrayList<String>();
for (int i = 0; i < checked.size(); i++) {
// Item position in adapter
int position = checked.keyAt(i);
// Add sport if it is checked i.e.) == TRUE!
if (checked.valueAt(i))
selectedItems.add((String) adapter.getItem(position));
}
final String[] outputStrArr = new String[selectedItems.size()];
for (int i = 0; i < selectedItems.size(); i++) {
outputStrArr[i] = selectedItems.get(i);
Log.d("teste", String.valueOf(i));
}
Log.e("teste", "chega aqui ?===??");
new Get(outputStrArr).execute();
Log.e("teste", String.valueOf(getid.size()));
String[] teste = new String[getid.size()];
Log.e("teste", "chega aqui ?===??");
for (int f = 0; f < getid.size();f++){
teste[f] = getid.get(f);
Log.d("teste", "welelelelelele ?");
}
for (int va = 0; va < teste.length;va++){
Log.d("teste", "adadada ?");
pls +=teste[va];
}
editText.setText(pls);
Intent x = new Intent(AddCenario.this, GerirCenario.class);
Bundle b = new Bundle();
b.putStringArray("selectedItems", outputStrArr);
String text = editText.getText().toString();
x.putExtra("ola" , text);
x.putExtras(b);
startActivity(x);
listView.getSelectedItem();
}
});
}
private class Get extends AsyncTask<String, Void, Void> {
private final String[] outputStrArr;
Get(String[] outputStrArr)
{
this.outputStrArr = outputStrArr;
}
#Override
protected void onPreExecute() {
}
#Override
protected Void doInBackground(String... integers) {
for (x = 0; x < outputStrArr.length; x++) {
try {
RequestQueue queue = Volley.newRequestQueue(AddCenario.this);
String url = "" + outputStrArr[x];
JsonArrayRequest jsonRequest = new JsonArrayRequest
(Request.Method.GET, url, null, new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
try {
for (int i = 0; i < response.length(); ++i) {
JSONObject obj = response.getJSONObject(i);
id[0] = obj.getString("id");
getid.add(id[0]);
Log.d("teste", "chega aqui ?");
Log.e("teste", String.valueOf(getid.size()));
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
error.printStackTrace();
}
});
queue.add(jsonRequest);
} catch (Exception ex) {
}
}
return null;
}
protected void onPostExecute(Void result) {
super.onPostExecute(result);
}
}
}

Marker.remove() is not working in google map, I want to remove the marker outside the radius?

in my application I am using list of markers but when I tried to remove the marker its not removing the marker.
Marker.remove() is not working in google map, I want to remove the marker outside the radius.
Please help
My source code is given below :
public class MapFragment extends Fragment implements LocationListener
{
private static final String LOG_TAG = "ExampleApp";
private MapView mMapView;
private GoogleMap mMap;
private Bundle mBundle;
private static final String SERVICE_URL = "http://203.187.247.199/primevts/vtsservice.svc/data";
JSONObject json = null;
JSONObject jsonobject = null;
JSONObject jsonobject1 =null;
JSONObject jsonobject2 =null;
JSONObject ja = null;
JSONArray jsonarray = null;
JSONArray jsonarray1 = null;
JSONArray jsonarray2 = null;
ProgressDialog mProgressDialog;
ArrayList<HashMap<String, String>> arraylist1;
ArrayList<HashMap<String, String>> arraylist11;
ArrayList<HashMap<String, String>> arraylist12;
ArrayList<HashMap<String, String>> arraylist;
List<Marker> markerList = new ArrayList<Marker>();
private Timer timer;
static String LONG = "Long";
static String LAT = "Lat";
ArrayList<String> ct;
public double latt = 0;
public double lng = 0;
public ArrayList<Integer> dLat;
private AlarmManager alarmMgr;
private PendingIntent alarmIntent;
private Handler handler;
public Marker marker;
Marker stop = null;
String RegistrationNo="";
LatLng destination,source,destination2,center;
Polyline polylin;
String ime1,destname,routeid;
GMapV2GetRouteDirection md;
private HashMap<String, Marker> mMarkers = new HashMap<>();
int value=1;
// LatLngBounds values ;
double latitude, longitude,destlat,destlong,sourcelat,sourcelong,destlat2,destlong2;
String ime,reg,regi;
Geocoder geocoder;
List<Address> addresses;
CircleOptions circleOptions;
Circle circle;
// LatLng val;
float[] distance = new float[2];
static HashMap<String, String> datas;
static HashMap<String, String> map;
String[] latlngvalues;
// LocationManager locman;
Context context;
View rootView;
ImageView imageView1;
TextView Address;
public MapFragment() {
}
#Override
public View onCreateView(final LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
rootView = inflater.inflate(R.layout.fragment_layout_one, container, false);
MapsInitializer.initialize(getActivity());
mMapView = (MapView)rootView.findViewById(R.id.mapView);
Address=(TextView)rootView.findViewById(R.id.adressText);
//imageView1=(ImageView) rootView.findViewById(R.id.imageView1);
mMapView.onCreate(mBundle);
MapsInitializer.initialize(getActivity());
if (android.os.Build.VERSION.SDK_INT > 9) {
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder()
.permitAll().build();
StrictMode.setThreadPolicy(policy);
}
new DownloadJSON().execute();
setUpMapIfNeeded(rootView);
new DestinationJSON().execute();
mMap.setInfoWindowAdapter(new InfoWindowAdapter() {
#Override
public View getInfoContents(Marker marker) {
// TODO Auto-generated method stub
return null;
}
#Override
public View getInfoWindow(Marker marker) {
// TODO Auto-generated method stub
View v = getActivity().getLayoutInflater().inflate(R.layout.info_window_layout, null);
TextView markerLabel = (TextView)v.findViewById(R.id.ime);
TextView destiname=(TextView)v.findViewById(R.id.destname);
TextView route=(TextView)v.findViewById(R.id.routeid);
markerLabel.setText(regi);
destiname.setText(destname);
route.setText(routeid);
Log.e("imeid", ""+ime1);
return v;
}
});
/* handler = new Handler();
handler.postDelayed(new Runnable() {
#Override
public void run() {
// TODO Auto-generated method stub
new DownloadJSON().execute();
setUpMapIfNeeded(rootView);
Toast.makeText(getActivity(), "Data Updated!!!! ", Toast.LENGTH_SHORT).show();
Log.e("Data in Log", "");
}
}, 1000);
*/
final Handler handler = new Handler();
timer = new Timer();
TimerTask doAsynchronousTask = new TimerTask() {
#Override
public void run() {
handler.post(new Runnable() {
public void run() {
//mMap.clear();
//Toast.makeText(getActivity(), "Data Updated!!!! ", Toast.LENGTH_SHORT).show();
new DownloadJSON().execute();
setUpMapIfNeeded(rootView);
}
});
}
};
timer.schedule(doAsynchronousTask, 20000, 20000);
/*LocationManager locman = (LocationManager)getActivity().getSystemService(Context.LOCATION_SERVICE);
//locman.requestLocationUpdates(minTime, minDistance, criteria, intent);
locman.requestLocationUpdates(LocationManager.GPS_PROVIDER, 1000, 10, this);*/
return rootView;
}
private void setUpMapIfNeeded(View inflatedView) {
if (mMap == null) {
mMap = ((MapView) inflatedView.findViewById(R.id.mapView)).getMap();
mMap.setMyLocationEnabled(true);
Location myLocation = mMap.getMyLocation();
if (mMap != null) {
//mMap.clear();
mMap.setOnCameraChangeListener(new OnCameraChangeListener() {
#Override
public void onCameraChange(final CameraPosition arg0) {
mMap.setOnMapLoadedCallback(new GoogleMap.OnMapLoadedCallback() {
#Override
public void onMapLoaded() {
LatLng latLng= mMap.getCameraPosition().target;
double lat = latLng.latitude;
double lng = latLng.longitude;
Log.e("lati",""+lat);
Log.e("longi",""+lng);
Log.d("TAG", latLng.toString());
//mMap.clear();
if(circle!=null){
circle.remove();
//mMap.clear();
}
circleOptions = new CircleOptions();
circleOptions.center(latLng);
//circleOptions.fillColor(Color.TRANSPARENT);
circleOptions.radius(10000);
circleOptions.strokeColor(Color.TRANSPARENT);
circle = mMap.addCircle(circleOptions);
Log.e("",""+circle);
center = mMap.getCameraPosition().target;
new GetLocationAsync(center.latitude, center.longitude).execute();
/* geocoder = new Geocoder(getActivity(), Locale.getDefault());
try {
addresses = geocoder.getFromLocation(lat, lng, 1);
String address = addresses.get(0).getAddressLine(0); // If any additional address line present than only, check with max available address lines by getMaxAddressLineIndex()
Log.e("address",""+address);
String city = addresses.get(0).getLocality();
Log.e("city",""+city);
String state = addresses.get(0).getAdminArea();
Log.e("state",""+state);
String country = addresses.get(0).getCountryName();
Log.e("contry",""+country);
String postalCode = addresses.get(0).getPostalCode();
Log.e("postalcode",""+postalCode);
String knownName = addresses.get(0).getFeatureName();
Log.e("knownName",""+knownName);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} // Here 1 represent max location result to returned, by documents it recommended 1 to 5
//Toast.makeText(this, latLng.toString(), Toast.LENGTH_LONG).show();
}*/
}
});
}
});
mMap.setOnMarkerClickListener(new OnMarkerClickListener() {
#Override
public boolean onMarkerClick(Marker arg0) {
// TODO Auto-generated method stub
if(stop!=null){
mMap.clear();
}
regi=arg0.getTitle().toString();
Log.e("aaa", ""+regi);
JSONPost jsonpost= new JSONPost();
ja=jsonpost.datewise(regi);
Log.e("Home_details..", "" + ja);
// new DownloadJSON2().execute();
try
{
arraylist11 = new ArrayList<HashMap<String, String>>();
arraylist12 = new ArrayList<HashMap<String, String>>();
jsonarray = ja.getJSONArray("Routeinbus");
for (int i = 0; i <jsonarray.length(); i++) {
HashMap<String, String> map = new HashMap<String, String>();
json = jsonarray.getJSONObject(i);
Log.e("G>>>>>>>>>>>", "" + json);
// Retrive JSON Objects
// map.put("flatID", jsonobject.getString("flatID"));
map.put("FromLat", json.getString("FromLat"));
map.put("FromLong", json.getString("FromLong"));
sourcelat = json.getDouble("FromLat");
sourcelong=json.getDouble("FromLong");
source=new LatLng(sourcelat, sourcelong);
map.put("Fromaddress", json.getString("Fromaddress"));
map.put("ToLat", json.getString("ToLat"));
map.put("ToLong", json.getString("ToLong"));
routeid=json.getString("RouteID");
destname=json.getString("Toaddress");
destlat2=json.getDouble("ToLat");
destlong2=json.getDouble("ToLong");
destination2=new LatLng(destlat2, destlong2);
jsonarray1 = json.getJSONArray("Routes");
Log.d("Hbbbbbbbbbbbbbbb", "" + jsonarray1);
for (int j = 0; j <jsonarray1.length(); j++) {
jsonobject1 = jsonarray1.getJSONObject(j);
jsonarray2=jsonobject1.getJSONArray("stages");
Log.d("jsonarray2", "" + jsonarray2);
for(int k=0;k<jsonarray2.length();k++)
{
jsonobject2 =jsonarray2.getJSONObject(k);
HashMap<String, String> map1 = new HashMap<String, String>();
map1.put("Lat",jsonobject2.getString("Lat"));
Log.d("Hbbbbbbbbbbbbbbb", "" + jsonobject2.getString("Lat"));
map1.put("Long",jsonobject2.getString("Long"));
map1.put("StopName", jsonobject2.getString("StopName"));
Log.d("Hbbbbbbbbbbbbbbb", "" + jsonobject2.getString("Long"));
// map1.put("LiveLongitude",jsonobject1.getString("LiveLongitude"));
// Log.d("Hbbbbbbbbbbbbbbb", "" + jsonobject1.getString("LiveLongitude"));
arraylist12.add(map1);
Log.e("arraylist12", ""+arraylist12);
/*if(polylin!=null){
polylin.remove();
}
if(marker!=null){
marker.remove();
}
md = new GMapV2GetRouteDirection();
Document doc = md.getDocument(source, destination2,
GMapV2GetRouteDirection.MODE_DRIVING);
ArrayList<LatLng> directionPoint = md.getDirection(doc);
PolylineOptions rectLine = new PolylineOptions().width(10).color(
Color.CYAN);
for (int a = 0; a < directionPoint.size(); a++) {
rectLine.add(directionPoint.get(a));
}
polylin = mMap.addPolyline(rectLine);*/
//marker=mMap.addMarker(new MarkerOptions().position(destination2).icon(BitmapDescriptorFactory .fromResource(R.drawable.bustour)));
for (int m = 0; m < arraylist12.size(); m++)
{
final LatLng stopposition = new LatLng(Double .parseDouble(arraylist12.get(m).get("Lat")),Double.parseDouble(arraylist12.get(m).get("Long")));
Log.e("position", ""+stopposition);
String stopname = arraylist12.get(m).get("StopName");
Log.e("markcheck",""+stopname);
final MarkerOptions options = new MarkerOptions().position(stopposition).icon(BitmapDescriptorFactory .fromResource(R.drawable.greenbus)).title(stopname);
//mMap.addMarker(options);
stop=mMap.addMarker(options);
}
}
}
arraylist11.add(map);
Log.e("arraylist11",""+arraylist11);
}
}catch (Exception e) {
String result = "Error";
}
return false;
}
});
// setUpMap();
mMap.setOnMyLocationChangeListener(new GoogleMap.OnMyLocationChangeListener() {
#Override
public void onMyLocationChange(Location arg0) {
// TODO Auto-generated method stub
final LatLngBounds.Builder builder = new LatLngBounds.Builder();
// mMap.clear();
/* if(marker!=null){
marker.remove();
}*/
for (int i = 0; i < arraylist1.size(); i++) {
final LatLng position = new LatLng(Double
.parseDouble(arraylist1.get(i).get("Latitude")),
Double.parseDouble(arraylist1.get(i).get(
"Longitude")));
Double lati=Double.parseDouble(arraylist1.get(i).get("Latitude"));
Double longi=Double.parseDouble(arraylist1.get(i).get("Longitude"));
// Log.e("doublelati",""+lati);
// Log.e("doublelongi",""+longi);
ime1 = arraylist1.get(i).get("RegistrationNo");
final MarkerOptions options = new MarkerOptions()
.position(position);
//mMap.addMarker(options);
//marker=mMap.addMarker(new MarkerOptions().position(position).icon(BitmapDescriptorFactory .fromResource(R.drawable.buspng)));
// mMap.setInfoWindowAdapter(new MarkerInfoWindowAdapter());
//marker.showInfoWindow();
try
{
Location.distanceBetween(lati,longi,circle.getCenter().latitude, circle.getCenter().longitude, distance);
if ( distance[0] <= circle.getRadius())
{
marker=mMap.addMarker(options.icon(BitmapDescriptorFactory .fromResource(R.drawable.whitebus)).anchor(0.0f, 1.0f).title(ime1));
// Inside The Circle
}
else
{
//Toast.makeText(getActivity(), "currently no buses available at this location", Toast.LENGTH_SHORT).show();
/* if(marker!=null)
{
marker.remove();
}*/
// Outside The Circle
marker.remove();
}
}catch (Exception e){
}
//options.title(ime1);
builder.include(position);
} if(value==1){
LatLng latLng = new LatLng(arg0.getLatitude(), arg0
.getLongitude());
//mMap.setMapType(GoogleMap.MAP_TYPE_HYBRID);
mMap.setMyLocationEnabled(true);
//mMap.moveCamera(CameraUpdateFactory.newLatLng(newLatLnglatLng));
// mMap.setOnMapClickListener(null);
//mMap.animateCamera(CameraUpdateFactory.zoomTo(9));
CameraPosition cameraPosition = new CameraPosition.Builder()
.target(latLng) // Sets the center of the map to Mountain View
.zoom(10) // Sets the zoom
.build(); // Creates a CameraPosition from the builder
mMap.animateCamera(CameraUpdateFactory.newCameraPosition(cameraPosition));
value++;
}
}
});
}
}
}
private class DestinationJSON extends AsyncTask<Void, Void, Void> {
String result="";
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected Void doInBackground(Void... params) {
try {
arraylist1 = new ArrayList<HashMap<String, String>>();
JSONParser jParser = new JSONParser();
String result = "";
json = jParser.getJSONFromUrl("http://beta.json-generator.com/api/json/get/NJMZPNSi");
try {
arraylist1.clear();
jsonarray = json.getJSONArray("SingleIMEs");
Log.d("Haaaaaaaaaaaa", "" + json);
for (int i = 0; i < jsonarray.length(); i++) {
Log.d("H11111111111111111111111111",
"" + jsonarray.length());
map = new HashMap<String, String>();
json = jsonarray.getJSONObject(i);
destlat = json.getDouble("Latitude");
destlong = json.getDouble("Longitude");
ime = json.getString("IME");
//reg=json.getString("RegistrationNo");
map.put("Latitude", json.getString("Latitude"));
Log.e("CHECKLAT",""+json.getString("Latitude") );
map.put("Longitude", json.getString("Longitude"));
Log.e("CHECKLONG",""+json.getString("Longitude") );
//map.put("RegistrationNo", json.getString("RegistrationNo"));
map.put("IME", json.getString("IME"));
destination=new LatLng(destlat, destlong); }
} catch (JSONException e) {
Log.e("log_tag", "Error parsing data " + e.toString());
result="Error";
e.printStackTrace();
}
}catch(Exception e){
result="Error";
}
return null;
}
protected void onPostExecute(Void args) {
// mProgressDialog.dismiss();
}
}
private class GetLocationAsync extends AsyncTask<String, Void, String> {
// boolean duplicateResponse;
double x, y;
StringBuilder str;
public GetLocationAsync(double latitude, double longitude) {
// TODO Auto-generated constructor stub
x = latitude;
y = longitude;
}
#Override
protected void onPreExecute() {
Address.setText(" Getting location ");
}
#Override
protected String doInBackground(String... params) {
// TODO Auto-generated method stub
try { geocoder = new Geocoder(getActivity(), Locale.ENGLISH);
addresses = geocoder.getFromLocation(x, y, 1);
str = new StringBuilder();
if (geocoder.isPresent()) {
Address returnAddress = addresses.get(0);
String localityString = returnAddress.getLocality();
String city = returnAddress.getCountryName();
String region_code = returnAddress.getCountryCode();
String zipcode = returnAddress.getPostalCode();
str.append(localityString + "");
str.append(city + "" + region_code + "");
str.append(zipcode + "");
} else {
}
} catch (Exception e) {
// TODO: handle exception
Log.e("tag", e.getMessage());
}
return null;
}
#Override
protected void onPostExecute(String result) {
try {
Address.setText(addresses.get(0).getAddressLine(0)
+ addresses.get(0).getAddressLine(1) + " ");
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
}
}
private class DownloadJSON extends AsyncTask<Void, Void, Void> {
String result="";
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected Void doInBackground(Void... params) {
try {
arraylist1 = new ArrayList<HashMap<String, String>>();
JSONParser jParser = new JSONParser();
String result = "";
json = jParser.getJSONFromUrl(SERVICE_URL);
try {
arraylist1.clear();
jsonarray = json.getJSONArray("SingleIMEs");
Log.d("Haaaaaaaaaaaa", "" + json);
for (int i = 0; i < jsonarray.length(); i++) {
Log.d("H11111111111111111111111111",
"" + jsonarray.length());
map = new HashMap<String, String>();
json = jsonarray.getJSONObject(i);
latitude = json.getDouble("Latitude");
longitude = json.getDouble("Longitude");
ime = json.getString("IME");
reg=json.getString("RegistrationNo");
map.put("Latitude", json.getString("Latitude"));
Log.e("CHECKLAT",""+json.getString("Latitude") );
map.put("Longitude", json.getString("Longitude"));
Log.e("CHECKLONG",""+json.getString("Longitude") );
map.put("RegistrationNo", json.getString("RegistrationNo"));
map.put("IME", json.getString("IME"));
arraylist1.add(map);
//Log.e("arraylist1", ""+arraylist1);
}
} catch (JSONException e) {
Log.e("log_tag", "Error parsing data " + e.toString());
result="Error";
e.printStackTrace();
}
}catch(Exception e){
result="Error";
}
return null;
}
protected void onPostExecute(Void args) {
// mProgressDialog.dismiss();
}
}
#Override
public void onResume() {
super.onResume();
mMapView.onResume();
}
#Override
public void onPause() {
super.onPause();
mMapView.onPause();
}
#Override
public void onLowMemory() {
super.onLowMemory();
mMapView.onLowMemory();
}
#Override
public void onDestroy() {
mMapView.onDestroy();
super.onDestroy();
}
#Override
public void onLocationChanged(Location location) {
// TODO Auto-generated method stub
/* Toast.makeText(getActivity(), "onLocationUpdated!!!", Toast.LENGTH_SHORT).show();
Log.d("onLocationUpdated!!!","");
new DownloadJSON().execute();
setUpMapIfNeeded(rootView);*/
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
// TODO Auto-generated method stub
}
#Override
public void onProviderEnabled(String provider) {
// TODO Auto-generated method stub
}
#Override
public void onProviderDisabled(String provider) {
// TODO Auto-generated method stub
} {
}
}

JSON parsing android

I need advice about my code.
I'm trying to parse a JSON array generated by the PHP function json_encode().
My json:
{"data": [{"streamer":"froggen","yt_length":"25078"},{"streamer":"wingsofdeath","yt_length":"8979"},{"streamer":"guardsmanbob","yt_length":"4790"},{"streamer":"kaostv","yt_length":"4626"},{"streamer":"kungentv","yt_length":"3883"},{"streamer":"destiny","yt_length":"3715"},{"streamer":"zekent","yt_length":"3428"},{"streamer":"athenelive","yt_length":"1673"},{"streamer":"frommaplestreet","yt_length":"1614"},{"streamer":"keyorikeys","yt_length":"1410"},{"streamer":"riotgamesturkish","yt_length":"1397"},{"streamer":"vman7","yt_length":"1022"},{"streamer":"tiensinoakuma","yt_length":"967"},{"streamer":"affenklappe","yt_length":"748"},{"streamer":"teamkeyd","yt_length":"747"},{"streamer":"lagtvmaximusblack","yt_length":"683"},{"streamer":"lolgameru","yt_length":"665"},{"streamer":"gruntartv","yt_length":"585"},{"streamer":"entenzwerg","yt_length":"579"},{"streamer":"lolgameru_cauthonpro","yt_length":"506"},{"streamer":"basickz","yt_length":"488"},{"streamer":"ilysuiteheart","yt_length":"491"},{"streamer":"kireiautumn","yt_length":"485"},{"streamer":"ultimavv","yt_length":"471"}]}
Java class:
public class JSONParser {
static InputStream is = null;
static JSONObject jObj = null;
static String json = "";
String response = "";
// constructor
public JSONParser() {
}
public JSONObject getJSONFromUrl(String url) {
// Making HTTP request
try {
// defaultHttpClient
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpGet httpPost = new HttpGet(url);
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(
is), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
json = sb.toString();
} catch (Exception e) {
Log.e("Buffer Error", "Error converting result " + e.toString());
}
// try parse the string to a JSON object
try {
jObj = new JSONObject(json);
} catch (JSONException e) {
Log.e("JSON Parser", "Error parsing data " + e.toString());
}
// return JSON String
return jObj;
}
}
And my activity:
public class AndroidJSONParsingActivity extends ListActivity {
// url to make request
private static String url = "http://ololo.tv/vasa";
// JSON Node names
private static final String TAG_DATA = "data";
private static final String TAG_STREAMER = "streamer";
private static final String TAG_VIEWERS = "yt_length";
// contacts JSONArray
JSONArray data = null;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
// Hashmap for ListView
ArrayList<HashMap<String, String>> dataList = new ArrayList<HashMap<String, String>>();
// Creating JSON Parser instance
JSONParser Parser = new JSONParser();
// getting JSON string from URL
JSONObject json = null;
json = Parser.getJSONFromUrl(url);
try {
// Getting Array of Contacts
data = json.getJSONArray(TAG_DATA);
// looping through All Contacts
for(int i = 0; i < data.length(); i++){
JSONObject c = data.getJSONObject(i);
// Storing each json item in variable
String streamer = c.getString(TAG_STREAMER);
String viewers = c.getString(TAG_VIEWERS);
//String link = c.getString();
// creating new HashMap
HashMap<String, String> map = new HashMap<String, String>();
// adding each child node to HashMap key => value
map.put(TAG_STREAMER, streamer);
map.put(TAG_VIEWERS, viewers);
//map.put(TAG_URL, link);
// adding HashList to ArrayList
dataList.add(map);
}
} catch (JSONException e) {
e.printStackTrace();
}
/**
* Updating parsed JSON data into ListView
* */
ListAdapter adapter = new SimpleAdapter(this, dataList,
R.layout.list_item,
new String[] { TAG_STREAMER, TAG_VIEWERS /*TAG_URL*/ }, new int[] {
R.id.streamer, R.id.viewers /*R.id.url*/ });
setListAdapter(adapter);
// selecting single ListView item
ListView lv = getListView();
// Launching new screen on Selecting Single ListItem
lv.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// getting values from selected ListItem
String name = ((TextView) view.findViewById(R.id.streamer)).getText().toString();
String viewers_count = ((TextView) view.findViewById(R.id.viewers)).getText().toString();
//String url = ((TextView) view.findViewById(R.id.url)).getText().toString();
// Starting new intent
Intent in = new Intent(getApplicationContext(), SingleMenuItemActivity.class);
in.putExtra(TAG_STREAMER, name);
in.putExtra(TAG_VIEWERS, viewers_count);
//in.putExtra(TAG_PHONE_MOBILE, url);
startActivity(in);
}
});
}
}
I tried using breakpoints, and see that when I put a breakpoint after GetEntity, the program doesn't get there because it crashed early, or something.
This my async task.
public class ParsingTask extends AsyncTask<String, Void, Void>{
JSONParser Parser = new JSONParser();
protected Void doInBackground(String... urls) {
ArrayList<HashMap<String, String>> dataList = new ArrayList<HashMap<String, String>>();
JSONObject json = Parser.getJSONFromUrl(url);
try {
// Getting Array of Contacts
data = json.getJSONArray(TAG_DATA);
// looping through All Contacts
for(int i = 0; i < data.length(); i++){
JSONObject c = data.getJSONObject(i);
// Storing each json item in variable
String streamer = c.getString(TAG_STREAMER);
String viewers = c.getString(TAG_VIEWERS);
//String link = c.getString();
// creating new HashMap
HashMap<String, String> map = new HashMap<String, String>();
// adding each child node to HashMap key => value
map.put(TAG_STREAMER, streamer);
map.put(TAG_VIEWERS, viewers);
//map.put(TAG_URL, link);
// adding HashList to ArrayList
dataList.add(map);
}
} catch (JSONException e) {
e.printStackTrace();
}
/**
* Updating parsed JSON data into ListView
* */
ListAdapter adapter = new SimpleAdapter(this, dataList,
R.layout.list_item,
new String[] { TAG_STREAMER, TAG_VIEWERS /*TAG_URL*/ }, new int[] {
R.id.streamer, R.id.viewers /*R.id.url*/ });
setListAdapter(adapter);
return null;
}
protected void onProgressUpdate() {
}
protected void onPostExecute() {
}
}
ListAdapter error, seems like something wrong in "this". This my version how cut off code, where it stop return variables. Sorry for bad english, but i hope you understand me :)
Add my php json maker. Mb problem there?!
<?php
mysql_connect("localhost","root","");
if (!mysql_select_db("ololo")) {
echo "Unable to select ololo: " . mysql_error();
}
$sql=mysql_query("select streamer, yt_length from pm_videos where category='1'");
if(!$sql) exit("Error - ".mysql_error().", ".$tmp_q);
while($row=mysql_fetch_assoc($sql)){
$output[]=$row;
}
$json = json_encode($output);
header('Content-Type: application/json');
print "{\"data\": ${json}}";
mysql_close();
?>
You programm crashes because you are running
json = Parser.getJSONFromUrl(url);
in the UI Thread context. You have to use an AsyncTask
Code looks good. The only problem is that
public class ParsingTask extends AsyncTask<String, Void, ArrayList<HashMap<String, String>>>{
JSONParser Parser = new JSONParser();
protected Void doInBackground(String... urls) {
ArrayList<HashMap<String, String>> dataList = new ArrayList<HashMap<String, String>>();
JSONObject json = Parser.getJSONFromUrl(url);
try {
// Getting Array of Contacts
data = json.getJSONArray(TAG_DATA);
// looping through All Contacts
for(int i = 0; i < data.length(); i++){
JSONObject c = data.getJSONObject(i);
// Storing each json item in variable
String streamer = c.getString(TAG_STREAMER);
String viewers = c.getString(TAG_VIEWERS);
//String link = c.getString();
// creating new HashMap
HashMap<String, String> map = new HashMap<String, String>();
// adding each child node to HashMap key => value
map.put(TAG_STREAMER, streamer);
map.put(TAG_VIEWERS, viewers);
//map.put(TAG_URL, link);
// adding HashList to ArrayList
dataList.add(map);
}
} catch (JSONException e) {
e.printStackTrace();
}
/**
* Updating parsed JSON data into ListView
* */
return dataList;
}
protected void onPostExecute(ArrayList<HashMap<String, String>> dataList) {
ListAdapter adapter = new SimpleAdapter(AndroidJSONParsingActivity.this, dataList,
R.layout.list_item,
new String[] { TAG_STREAMER, TAG_VIEWERS /*TAG_URL*/ }, new int[] {
R.id.streamer, R.id.viewers /*R.id.url*/ });
setListAdapter(adapter);
}
Have you heard about gson (docs)?
public static final class Content {
#SerializedName("streamer") // you don't need to specify this, JFYI
String streamer;
#SerializedName("yt_length") // you don't need to specify this, JFYI
String yt_length;
}
public static final class Data {
#SerializedName("data")
List<Content> data;
}
public static void main (String[] args) {
Gson gson = new GsonBuilder().create();
Data data = gson.fromJson(jsonString, Data.class);
}
And remember, you cannot call network operations on UI thread! this is reason of what you have for now.
json data
[
-{
Cat_Id: 21
Cat_Title: "Electronics"
Cat_Description: null
Cat_Status: 0
Cat_CreatedBy: 0
Cat_CreatedDate: "0001-01-01T00:00:00"
Cat_UpdatedBy: 0
Cat_UpdatedDate: "0001-01-01T00:00:00"
}
Category class
public class Category {
public int Cat_Id;
public String Cat_Title = null;;
public Category() {
}
public int getCat_Id() {
return Cat_Id;
}
public void setCat_Id(int Cat_Id) {
this.Cat_Id = Cat_Id;
}
}
BaseActivity
public class BaseActivity extends Activity {
public ProgressDialog progressDialog;
public SharedPreferences prefs;
public JSONObject jsonObject;
public JSONObject jsonObject1;
public static String pref_setting = "Category_setting";
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// TODO Auto-generated method stub
progressDialog = new ProgressDialog(this);
progressDialog.setMessage("Loading..");
prefs = PreferenceManager.getDefaultSharedPreferences(this);
Preferences.AppContext = this;
}
protected void onStop() {
super.onStop();
if (progressDialog != null && progressDialog.isShowing()) {
progressDialog.dismiss();
}
}
}
Soap
public class Soap {
// public static String BaseURL = "";
public static String BaseURL = "";
public static String imgURL = "";
public static String getSoapResponseByGet(String postFixOfUrl)
throws ClientProtocolException, IOException {
if (Preferences.AppContext != null
&& Preferences.isOnline(Preferences.AppContext)) {
HttpClient httpclient = new DefaultHttpClient();
HttpGet httpget = new HttpGet(BaseURL + postFixOfUrl);
HttpResponse response = httpclient.execute(httpget);
HttpEntity entity = response.getEntity();
String xmlString = EntityUtils.toString(entity);
return xmlString.toString();
} else {
return "{\"error\":{\"no_internet\":\"No internet connection\"}}";
}
}
public static String getSoapResponse(String postFixOfUrl)
throws ClientProtocolException, IOException {
if (Preferences.AppContext != null
&& Preferences.isOnline(Preferences.AppContext)) {
HttpPost httpPost = new HttpPost(BaseURL + postFixOfUrl);
StringEntity se = new StringEntity("", HTTP.UTF_8);
se.setContentType("text/xml");
httpPost.setHeader("Content-Type", "text/xml;charset=utf-8");
httpPost.setEntity(se);
HttpClient httpClient = new DefaultHttpClient();
BasicHttpResponse httpResponse = (BasicHttpResponse) httpClient
.execute(httpPost);
HttpEntity r_Entity = httpResponse.getEntity();
String xmlString = EntityUtils.toString(r_Entity);
return xmlString.toString();
} else {
return "{\"error\":{\"no_internet\":\"No internet connection\"}}";
}
}
public static String getSoapResponseByPost(String postFixOfUrl,
ArrayList<NameValuePair> nameValuePairs)
throws ClientProtocolException, IOException {
if (Preferences.AppContext != null
&& Preferences.isOnline(Preferences.AppContext)) {
HttpPost httpPost = new HttpPost(BaseURL + postFixOfUrl);
httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs, "UTF-8"));
HttpClient httpClient = new DefaultHttpClient();
BasicHttpResponse httpResponse = (BasicHttpResponse) httpClient
.execute(httpPost);
HttpEntity r_Entity = httpResponse.getEntity();
String xmlString = EntityUtils.toString(r_Entity);
return xmlString.toString();
} else {
return "{\"error\":{\"no_internet\":\"No internet connection\"}}";
}
}
// ////////// api for Category //////////////
http://sharafdg.digitarabia.com/sharafdg/api/Category
public static String apiGetCategory() throws ClientProtocolException,
IOException {
String result = Soap.getSoapResponseByGet("api/Category");
Log.e("SOAP", result);
return result;
}
public static String apiGetstore(int catid, int brandid, int modelid,
String variant) throws ClientProtocolException, IOException {
String result = Soap.getSoapResponseByGet("api/stores/?catid=" + catid
+ "&brandid=" + brandid + "&modelid=" + modelid + "&variant="
+ variant);
Log.e("SOAPSTORE", "api/stores/?catid=" + catid);
Log.e("SOAPSTORE", "api/stores/?&brandid=" + brandid);
Log.e("SOAPSTORE", "api/stores/?&modelid=" + modelid);
Log.e("SOAPSTORE", "api/stores/?&variant=" + variant);
return result;
}
-------------- post method hoy to -----------------
http://kallapp.madword-media.co.uk/company.php?category_id=11
http://kallapp.madword-media.co.uk/categories.php
public static String apiGetCategory() throws ClientProtocolException,
IOException {
ArrayList<NameValuePair> alNameValuePairs = new
ArrayList<NameValuePair>();
String result = Soap.getSoapResponseByPost("categories.php",
alNameValuePairs);
return result;
}
public static String apiGetcompanies(String category_id)
throws ClientProtocolException, IOException {
ArrayList<NameValuePair> alNameValuePairs = new
ArrayList<NameValuePair>();
// NameValuePair nameValuePairs = new BasicNameValuePair("",
// category_id);
// alNameValuePairs.add(nameValuePairs);
String result = Soap.getSoapResponse("company.php?category_id="
+ category_id);
Log.e("SOAP", result);
return result;
}
public static String apiGetDepaName(String category_id, String
company_id)
throws ClientProtocolException, IOException {
ArrayList<NameValuePair> alNameValuePairs = new
ArrayList<NameValuePair>();
NameValuePair nameValuePair = new BasicNameValuePair("category_id",
category_id);
alNameValuePairs.add(nameValuePair);
nameValuePair = new BasicNameValuePair("company_id", company_id);
alNameValuePairs.add(nameValuePair);
String result =
Soap.getSoapResponseByPost("department.php?",alNameValuePairs);
return result;
}
Category_list
public class Category_list extends BaseActivity {
int currentCategoryid;
private ArrayList<Category> cat = new ArrayList<Category>();
ArrayList<String> list = new ArrayList<String>();
Spinner spinner;
Button btncompare;
private int catid;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// TODO Auto-generated method stub
setContentView(R.layout.activity_webservices);
spinner = (Spinner) findViewById(R.id.spinner);
btncompare = (Button) findViewById(R.id.btncompare);
spinner.setOnItemSelectedListener(new OnItemSelected());
new getCategoryTask().execute();
btncompare.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent intent = new Intent(getBaseContext(), Store.class);
intent.putExtra("catid", catid);
startActivity(intent);
}
});
}
public class OnItemSelected implements OnItemSelectedListener {
public void onItemSelected(AdapterView<?> arg0, View arg1, int arg2,
long arg3) {
// ((TextView) arg0.getChildAt(0)).setTextColor(Color.GREEN);
catid = cat.get(arg2).Cat_Id;
String cateid = String.valueOf(catid);
Log.e("cateid_category", cateid);
// new getBrandTask().execute();
}
public void onNothingSelected(AdapterView<?> arg0) {
}
}
private class getCategoryTask extends AsyncTask<Void, Void, Void> {
Category category;
String categoryJsonStr;
public getCategoryTask() {
category = new Category();
}
protected void onPreExecute() {
super.onPreExecute();
// progressDialog.show();
}
#Override
protected Void doInBackground(Void... params) {
// TODO Auto-generated method stub
-----------------------admin email-pass-------------
JSONObject jsonObject = new JSONObject(userJsonStr);//
jsonUserArray.getJSONObject(i);
currentUserid = jsonObject.getInt("Use_Id");
if (currentUserid > 0) {
if (!jsonObject.isNull("Use_Id")) {
id = jsonObject.getInt("Use_Id");
}
}
--------------------kallapp---------
try {
Log.i("categoryJsonStr", categoryJsonStr);
JSONObject jsonObject = new JSONObject(categoryJsonStr);
JSONArray jsonCatArray = jsonObject.getJSONArray("categories");
for (int i = 0; i < jsonCatArray.length(); i++) {
Category objcategory = new Category();
jsonObject = jsonCatArray.getJSONObject(i);
--------------------------------------------------------------
try {
// categoryJsonStr = Soap.apiGetCategory();
Log.e("categoryJsonStr", categoryJsonStr);
JSONArray jsonCatArray = new JSONArray(categoryJsonStr);
Category category = new Category();
// category.Cat_Id = -1;
category.Cat_Title = "Select Category";
cat.add(category);
list.add(category.Cat_Title);
for (int i = 0; i < jsonCatArray.length(); i++) {
Category objcategory = new Category();
JSONObject jsonObject = jsonCatArray.getJSONObject(i);
currentCategoryid = jsonObject.getInt("Cat_Id");
if (!jsonObject.isNull("Cat_Title")) {
objcategory.setCat_Title(jsonObject
.getString("Cat_Title"));
}
if (!jsonObject.isNull("Cat_Id")) {
objcategory.setCat_Id(jsonObject.getInt("Cat_Id"));
}
cat.add(objcategory);
list.add(objcategory.Cat_Title);
}
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
return null;
}
public void onPostExecute(Void result) {
super.onPostExecute(result);
// progressDialog.dismiss();
spinner.setAdapter(new ArrayAdapter<String>(Category_list.this,
android.R.layout.simple_spinner_item, list));
spinner.setSelection(0, true);
}
}
}
-------------more than one item fill--------
store_lists.add(objStore_list);
public void onPostExecute(Void result) {
super.onPostExecute(result);
store_adapter = new Store_adapter(Store.this, store_lists);
lv_store.setAdapter(store_adapter);
store_adapter.notifyDataSetChanged();
}
Preferences
public class Preferences {
public static Context AppContext = null;
public static String categoryid;
public static boolean isOnline(Context c) {
ConnectivityManager cm = (ConnectivityManager) c
.getSystemService(Context.CONNECTIVITY_SERVICE);
return cm.getActiveNetworkInfo() != null
&& cm.getActiveNetworkInfo().isConnectedOrConnecting();
}
}
Store_adapter
private Context mContext;
private int ImageCount;
private ArrayList<Store_list> store_lists = new ArrayList<Store_list>();
public ImageLoader imageLoader;
ImageView imgsave, imgpackage, img_up_arrow, img_dun_arrow;
TextView txtsave;
RelativeLayout relatv;
public Store_adapter(Context c, ArrayList<Store_list> store_lists) {
mContext = c;
this.store_lists = store_lists;
this.ImageCount = store_lists.size();
imageLoader = new ImageLoader(c);
}
#Override
public int getCount() {
// TODO Auto-generated method stub
// ImageCount = store_lists.size();
return this.ImageCount;
}
#Override
public Object getItem(int arg0) {
// TODO Auto-generated method stub
return null;
}
#Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return 0;
}
public void notifyDataSetChanged() {
super.notifyDataSetChanged();
this.ImageCount = store_lists.size();
}
public void remove(int position) {
store_lists.remove(position);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
LayoutInflater inflater = (LayoutInflater) mContext
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View vi = inflater.inflate(R.layout.storelist, parent, false);
TextView name = (TextView) vi.findViewById(R.id.txtprise);
ImageView imgview = (ImageView) vi.findViewById(R.id.imgve);
Store_list list = store_lists.get(position);
imageLoader.DisplayImage(list.Store_logo, imgview);
name.setText(String.valueOf(list.Mod_Price));
return vi;
}
}
menifestfile
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"
/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"
/>
public static String getSoapResponse(String postFixOfUrl) {
try {
if (General.AppContext != null
&& General.isOnline(General.AppContext)) {
HttpGet httpget = new HttpGet(BaseURL + postFixOfUrl);
Log.i("SOAP", "URI:" + BaseURL + postFixOfUrl);
httpget.setHeader("Content-Type",
"application/json;charset=utf-8");
HttpClient httpclient = new DefaultHttpClient();
BasicHttpResponse httpResponse = (BasicHttpResponse) httpclient
.execute(httpget);
HttpEntity r_entity = httpResponse.getEntity();
String xmlString = EntityUtils.toString(r_entity);
return xmlString.toString();
} else {
// return
// "[{\"erorr\":{\"no_internet\":\"No internet connection\"}}]";
if (General.AppActivity != null) {
General.AppActivity.runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(
General.AppContext,
General.AppContext
.getResources()
.getString(
R.string.no_internet_connection),
Toast.LENGTH_SHORT).show();
}
});
}
return null;
}
} catch (Exception e) {
HandleException.catchException(e, true);
}
return null;
}
// post method
public static String getSoapResponseByPost(String postFixOfUrl,
ArrayList<NameValuePair> nameValuePairs)
throws ClientProtocolException, IOException {
try {
if (General.AppContext != null
&& General.isOnline(General.AppContext)) {
HttpPost httppost = new HttpPost(BaseURL + postFixOfUrl);
Log.i("SOAP", "URI:" + BaseURL + postFixOfUrl);
// httppost.setHeader("Content-Type",
// "text/html;charset=utf-8");
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs,
"UTF-8"));
HttpClient httpclient = new DefaultHttpClient();
BasicHttpResponse httpResponse = (BasicHttpResponse) httpclient
.execute(httppost);
HttpEntity r_entity = httpResponse.getEntity();
String xmlString = EntityUtils.toString(r_entity);
return xmlString.toString();
} else {
// return
// "[{\"erorr\":{\"no_internet\":\"No internet connection\"}}]";
if (General.AppActivity != null) {
General.AppActivity.runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(
General.AppContext,
General.AppContext
.getResources()
.getString(
R.string.no_internet_connection),
Toast.LENGTH_SHORT).show();
}
});
}
return null;
}
} catch (Exception e) {
HandleException.catchException(e, true);
}
return null;
}
public static String getSoapResponseForImage(String postFixOfUrl,
List<NameValuePair> nameValuePairs,
List<NameValuePair> filenameValuePairs) {
String xmlString = null;
HttpClient httpClient = new DefaultHttpClient();
HttpContext localContext = new BasicHttpContext();
HttpPost httpPost = new HttpPost(BaseURL + postFixOfUrl);
try {
MultipartEntity entity = new MultipartEntity();
for (int index = 0; index < filenameValuePairs.size(); index++) {
File myFile = new File(filenameValuePairs.get(index).getValue());
if (myFile.exists()) {
FileBody fileBody = new FileBody(myFile);
entity.addPart(filenameValuePairs.get(index).getName(),
fileBody);
}
}
for (int index = 0; index < nameValuePairs.size(); index++) {
entity.addPart(nameValuePairs.get(index).getName(),
new StringBody(nameValuePairs.get(index).getValue(),
Charset.forName("UTF-8")));
}
httpPost.setEntity(entity);
HttpResponse response = httpClient.execute(httpPost, localContext);
HttpEntity r_entity = response.getEntity();
xmlString = EntityUtils.toString(r_entity);
} catch (IOException e) {
e.printStackTrace();
}
Log.d("SOAP ", "Result : " + xmlString.toString());
return xmlString.toString();
}
public class ParsedResponse {
public Object o;
public boolean error = false;
}
public class General {
public static Context AppContext = null;
public static Activity AppActivity = null;
public static boolean isOnline(Context c) {
ConnectivityManager cm = (ConnectivityManager) c
.getSystemService(Context.CONNECTIVITY_SERVICE);
return cm.getActiveNetworkInfo() != null
&& cm.getActiveNetworkInfo().isConnectedOrConnecting();
}}
public class BaseActivity extends Activity {
protected SharedPreferences prefs;
public ProgressDialog progressDialog;
General.AppContext = getApplicationContext();
General.AppActivity = BaseActivity.this;
prefs = PreferenceManager.getDefaultSharedPreferences(this);}
public class ErrorMgmt {
private Boolean error;
private String errorMessage;
private String exceptionMessage;
public ErrorMgmt(String exceptionMessage) {
error = false;
errorMessage = "";
this.exceptionMessage = exceptionMessage;
}
public ErrorMgmt() {
error = false;
errorMessage = "";
exceptionMessage = "";
}
public String getErrorMessage() {
if (error) {
if (errorMessage.equals("")) {
return exceptionMessage;
} else {
return errorMessage;
}
}
return null;
}
#SuppressWarnings("rawtypes")
public Boolean strError(String JsonResponse) {
this.error = false;
errorMessage = "";
try {
JSONObject objJson = new JSONObject(JsonResponse);
String strJson = objJson.getString("JsonResponse");
if(!strJson.equals("Please enter valid email")) {
this.error = true ;
errorMessage = "";
} else {
this.error = false;
}
} catch (JSONException e) {
this.error = true;
errorMessage = "";
HandleException.catchException(e, true);
}
return this.error;
}
#SuppressWarnings("rawtypes")
public Boolean isObjError(String JsonResponse) {
this.error = false;
errorMessage = "";
try {
JSONObject objJson = new JSONObject(JsonResponse);
if (objJson != null && !objJson.isNull("error") ) {
this.error = true;
Iterator IError = objJson.keys();
errorMessage = "";
while (IError.hasNext()) {
String key = (String) IError.next();
errorMessage += objJson.getString(key) + "\n";
}
} else if (objJson != null && !objJson.isNull("statusCode")) {
Integer statusCode = objJson.getInt("statusCode");
if (statusCode > 200) {
this.error = true;
} else {
this.error = false;
}
} else {
this.error = false;
}
} catch (JSONException e) {
this.error = true;
errorMessage = "";
HandleException.catchException(e, true);
}
return this.error;
}
#SuppressWarnings("rawtypes")
public Boolean isError(String JsonResponse) {
this.error = false;
errorMessage = "";
try {
JSONArray arrJson = new JSONArray(JsonResponse);
if (!arrJson.isNull(0) && !arrJson.getJSONObject(0).isNull("erorr")) {
this.error = true;
JSONObject objError = arrJson.getJSONObject(0);
Iterator IError = objError.keys();
errorMessage = "";
while (IError.hasNext()) {
String key = (String) IError.next();
errorMessage += objError.getString(key) + "\n";
}
} else if (!arrJson.isNull(0)
&& !arrJson.getJSONObject(0).isNull("statusCode")) {
Integer statusCode = arrJson.getJSONObject(0).getInt(
"statusCode");
if (statusCode > 200) {
this.error = true;
} else {
this.error = false;
}
} else {
this.error = false;
}
} catch (JSONException e) {
this.error = true;
errorMessage = "";
HandleException.catchException(e, true);
}
return this.error;
}
public void SetForsedError(Boolean val) {
error = true;
}
}
// Api for register with Email
public static ParsedResponse apiRegister(String name, String email,
String password) throws Exception {
ArrayList<NameValuePair> alNameValuePairs = new ArrayList<NameValuePair>();
NameValuePair nameValuePair = new BasicNameValuePair("name", name);
alNameValuePairs.add(nameValuePair);
nameValuePair = new BasicNameValuePair("email", email);
alNameValuePairs.add(nameValuePair);
nameValuePair = new BasicNameValuePair("password", password);
alNameValuePairs.add(nameValuePair);
// nameValuePair = new BasicNameValuePair("fb_uid", "");
// alNameValuePairs.add(nameValuePair);
String result = Soap.getSoapResponseByPost("user/register",
alNameValuePairs);
Log.e("apiRegister", result);
ErrorMgmt errMgmt = new ErrorMgmt(General.AppContext.getResources()
.getString(R.string.error_loading_data));
ParsedResponse p = new ParsedResponse();
p.error = false;
if (result != null && !result.equals("")) {
JSONObject jObject = new JSONObject(result);
String code = "";
if (!jObject.isNull("statusCode")) {
code = jObject.getString("statusCode");
}
if (code.equals("200")) {
JSONArray jsonArray = jObject.getJSONArray("User");
if (jsonArray.length() > 0) {
ArrayList<UserData> arrayList = new ArrayList<UserData>();
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObject = jsonArray.getJSONObject(i);
UserData objUserData = new UserData();
if (!jsonObject.isNull("uid")) {
objUserData.uid = jsonObject.getString("uid");
}
if (!jsonObject.isNull("name")) {
objUserData.name = jsonObject.getString("name");
}
if (!jsonObject.isNull("email")) {
objUserData.email = jsonObject.getString("email");
}
if (!jsonObject.isNull("password")) {
objUserData.password = jsonObject
.getString("password");
}
if (!jsonObject.isNull("created_date")) {
objUserData.created_date = jsonObject
.getString("created_date");
}
if (!jsonObject.isNull("status")) {
objUserData.status = jsonObject.getString("status");
}
if (!jsonObject.isNull("fb_uid")) {
objUserData.fb_uid = jsonObject.getString("fb_uid");
}
if (!jsonObject.isNull("account_type")) {
objUserData.account_type = jsonObject
.getString("account_type");
}
if (!jsonObject.isNull("profile_img")) {
objUserData.profile_img = jsonObject
.getString("profile_img");
}
if (!jsonObject.isNull("birthdate")) {
objUserData.birthdate = jsonObject
.getString("birthdate");
}
if (!jsonObject.isNull("city")) {
objUserData.city = jsonObject.getString("city");
}
JSONArray jsonArray2 = jsonObject
.getJSONArray("usersubscribe");
if (jsonArray2.length() > 0) {
for (int i1 = 0; i1 < jsonArray2.length(); i1++) {
JSONObject jsonObject2 = jsonArray2
.getJSONObject(i1);
if (!jsonObject2.isNull("isSubscribe")) {
objUserData.isSubscribe = jsonObject2
.getString("isSubscribe");
}
if (!jsonObject2.isNull("amount")) {
objUserData.amount = jsonObject2
.getString("amount");
}
}
}
arrayList.add(objUserData);
p.o = arrayList;
}
} else {
errMgmt = new ErrorMgmt(General.AppActivity.getResources()
.getString(R.string.err_norecords));
errMgmt.SetForsedError(true);
p.o = errMgmt;
p.error = true;
}
}
if (code.equals("401")) {
errMgmt = new ErrorMgmt(General.AppActivity.getResources()
.getString(R.string.allready_regi));
errMgmt.SetForsedError(true);
p.o = errMgmt;
p.error = true;
}
} else {
errMgmt = new ErrorMgmt(General.AppActivity.getResources()
.getString(R.string.err_norecords));
errMgmt.SetForsedError(true);
p.o = errMgmt;
p.error = true;
}
return p;
}
// Login with Facebook
private class GetFacebookLogin extends AsyncTask<Void, Void, Void> {
private ParsedResponse p = null;
private String message = "";
private Boolean error = false;
#Override
protected void onPreExecute() {
// TODO Auto-generated method stub
super.onPreExecute();
progressDialog.show();
}
#Override
protected Void doInBackground(Void... params) {
try {
p = new ParsedResponse();
p = Soap.apiUserLoginFacebook(fbID);
if (p.error) {
ErrorMgmt errmgmt = (ErrorMgmt) p.o;
message = errmgmt.getErrorMessage();
error = true;
} else {
arrayList.clear();
arrayList.addAll((ArrayList<UserData>) p.o);
error = false;
}
} catch (Exception e) {
message = "problem in loading data";
error = true;
}
return null;
}
#Override
protected void onPostExecute(Void result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
progressDialog.dismiss();
if (error) {
new AlertDialog.Builder(Register_Login_Screen.this)
.setMessage(message)
.setPositiveButton("Ok",
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog,
int which) {
dialog.dismiss();
}
}).show();
} else {
UserData objUserData = new UserData();
for (int i = 0; i < arrayList.size(); i++) {
objUserData = arrayList.get(i);
}
String profileImage = "";
try {
URL image_value = new URL("http://graph.facebook.com/"
+ fbID + "/picture?height=150&width=150");
profileImage = String.valueOf(image_value);
Log.e("fb_image_path", "" + image_value);
} catch (MalformedURLException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
Editor e = prefs.edit();
e.putBoolean(General.PREFS_login, true);
e.putString(General.PREFS_Uid, objUserData.uid);
e.putString(General.PREFS_name, objUserData.name);
e.putString(General.PREFS_email, objUserData.email);
e.putString(General.PREFS_fb_uid, objUserData.fb_uid);
e.putString(General.PREFS_logintype, General.PREFS_valuefblogin);
if (objUserData.profile_img != null
&& !objUserData.profile_img.equals("")) {
e.putString(General.PREFS_profile_img,
objUserData.profile_img);
} else {
e.putString(General.PREFS_profile_img, profileImage);
}
e.putString(General.PREFS_account_type,
objUserData.account_type);
e.putString(General.PREFS_birthdate, objUserData.birthdate);
e.putString(General.PREFS_city, objUserData.city);
e.putString(General.PREFS_subscribed, objUserData.isSubscribe);
e.putString(General.PREFS_amount, objUserData.amount);
String[] strings = null;
for (int i = 0; i < objUserData.screenerArr.size(); i++) {
String queString = objUserData.screenerArr.get(i);
strings = queString.split(",");
String question1 = strings[0];
e.putString("RosaRosa_screener_question" + (i + 1),
question1);
e.putBoolean("RosaRosa_screener_ans" + (i + 1), true);
String ans1 = strings[1];
e.putString(
"RosaRosa_screener_question" + (i + 1) + "_ans",
ans1);
Log.e("question", "" + question1 + ans1);
}
e.commit();
Toast.makeText(Register_Login_Screen.this, R.string.succ_login,
Toast.LENGTH_SHORT).show();
Intent intent = new Intent(Register_Login_Screen.this,
Personal_Stylist_Activity.class);
startActivity(intent);
finish();
}
}
}

Categories

Resources