map showing blur when i load the static map - android

when i load the static map using the URL, the map is displaying but its too much blur....kindly give the solution friends...Thanks in advance..........
Here is my code...
public class UpdateMap extends AsyncTask<String, String, String> {
#Override
protected String doInBackground(String... value) {
Double latter = Double.parseDouble(value[0]);
Double longer = Double.parseDouble(value[1]);
String address = value[2];
try {
String mapurl = "http://maps.google.com/maps/api/staticmap?center="
+ latter
+ ","
+ longer
+ "&zoom=15&size=100x100&sensor=true&markersize=55&markers=color:red%7Clabel:%7C"
+ latter + "," + longer;
double lat1 = Double.valueOf(latter);
double longt1 = Double.valueOf(longer);
Bitmap mapimage = BitmapConvert.bitmaptobitmap(application
.getGoogleMapThumbnail(lat1, longt1, mapurl));
Bitmap crop = crop(mapimage);
String mapimagestring = BitmapConvert.bitmaptostring(crop);
chatHistoryDB.updatemapimage(latter + "/" + longer + "/"
+ address, mapimagestring);
chatAdapter.doubletick();
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
}

Related

my table is full in class and empty in other

I'am a beginner in android and i use AndroidStudio
I have a problem
in have 2 class i my project in the first class "fetch compte" i fill my table "dataParsed" and i 'am certain that the table is fil
but in the second class MainActivity
I find that the table is empty
please help me
this is my code
public class fetchcompte extends AsyncTask<Void,Void,Void> {
String data = "";
String dat = "";
public static String[] dataParsed ;
String singleParsed ;
String dataParse = "";
String singleParse1 = "";
String singleParse2 = "";
String singleParse3 = "";
String singleParse4 = "";
String singleParse5 = "";
private RequestQueue mQueue, mQueu;
int nbcompte;
protected Void doInBackground(Void... voids) {
String S = jsonArray;
// singleParsed=new String[20];
dataParsed=new String[20];
try {
// String url2="http://recrutement.stb.com.tn:1010/PlateformeApi_Externe/api/ComptesClient/000001498675\n";
//String url2 = "http://10.1.11.168:8081/my/banks/10/accounts/10403082500589678844/transactions";
String url2 = "http://10.12.0.66:8081/api/ComptesClient/000001498675";
URL url = new URL(url2);
HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
InputStream inputStream = httpURLConnection.getInputStream();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
String line = "";
while (line != null) {
line = bufferedReader.readLine();
data = data + line;
}
JSONArray JA = new JSONArray(data);
nbcompte=JA.length();
for(int i =0 ;i<nbcompte; i++) {
JSONObject JO = (JSONObject) JA.get(i);
singleParsed = "fullname:" + JO.get("fullname");
singleParse1 = "accountnumber:" + JO.get("accountnumber");
singleParse2 = "rib:" + JO.get("rib");
singleParse3 = "iban:" + JO.get("iban");
singleParse4 = "name:" + JO.get("name");
singleParse5 = "balance:" + JO.get("balance");
dataParsed[i] = singleParsed + "\n" + singleParse1 + "\n" + singleParse2 + "\n" + singleParse3 + "\n" + singleParse4 + "\n" + singleParse5;
}
// dataParsed[i] =dataParsed[i] +singleParsed[i] +"\n" ;
// MainActivity.compte[i]=dataParsed[i];
// singleParsed[i] = "fullname:" + JO.get("fullname") + "\n"+
// "accountnumber:" + JO.get("accountnumber") + "\n"+
// "rib:" + JO.get("rib") + "\n"+
// "iban:" + JO.get("iban") + "\n"+
// "name:" + JO.get("name") + "\n"+
//"balance:" + JO.get("balance") + "\n";
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
for(int i =0 ;i <2; i++) {
// MainActivity.data.setText(this.d[i]);
}
}
//Authorization Bearer
my MainActivity
import static com.example.saiid.listecompte.fetchcompte.dataParsed;
public class MainActivity extends AppCompatActivity {
Button click;
public static TextView data;
public static String jsonArray;
private RequestQueue mQueue;
ImageView imageView2;
public static TextView textView_type;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mQueue = Volley.newRequestQueue(this);
click = (Button) findViewById(R.id.button_parse);
data = (TextView) findViewById(R.id.text_view_result);
click.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
setContentView(R.layout.listeview);
CustomAdaptercompte customAdapter=new CustomAdaptercompte();
ListView listeview=(ListView) findViewById(R.id.liste);
listeview.setAdapter(customAdapter);
fetchcompte process = new fetchcompte();
process.execute();
}
});
}
public class CustomAdaptercompte extends BaseAdapter {
#Override
public int getCount() {
return 2;
}
#Override
public Object getItem(int i) {
return null;
}
#Override
public long getItemId(int i) {
return 0;
}
#Override
public View getView(int i, View convertView, ViewGroup viewgrp) {
View view = getLayoutInflater().inflate(R.layout.customlayout,null);
imageView2 = (ImageView) view.findViewById(R.id.imageView2);
textView_type =(TextView) view.findViewById(R.id.textView_type);
imageView2.setImageResource(R.drawable.compte);
textView_type.setText(dataParsed[i]);
return view;
}
}
}
The mistake that you have made is that you assume that
import static com.example.saiid.listecompte.fetchcompte.dataParsed;
will automatically just be the dataParsed Variable you need. What that line does is that it gets the default value of dataParsed (from a default fetchcompte instance). Since you make another instance of a fetchcompte object [called process] (which you are using to populate its dataParsed variable) simply access the dataParsed variable of that instance.
So instead of using:
textView_type.setText(dataParsed[i]);
You can use:
textView_type.setText(process.dataParsed[i]);
But to do this you will need to somehow access the process variable in your adapter class.

Concatenation inside try catch

try {
final List<NetworkType> dataReceived = getData();
int i = 0;
//Array Iteration
for(final NetworkType networkType : dataReceived) {
i++;
if (i > 3) {
Toast.makeText(getApplicationContext(), "Done!!", Toast.LENGTH_SHORT);
} else {
String mCell1CID = networkType.getCell1CID();
String mCell1LAC = networkType.getCell1LAC();
String mCell1MCC = networkType.getCell1MCC();
String mCell1MNC = networkType.getCell1MNC();
String mCell1CI = networkType.getCell1CI();
String mCell1TAC = networkType.getCell1TAC();
//API requestBody
String url = "https://www.googleapis.com/geolocation/v1/geolocate?key=AIzaSyA8NAA3dUpECFn2j6pdcQT3wgqUM98UZ2Q";
String cellID = null;
String locationAreaCode = null;
if (mCell1CID.equals("") && mCell1LAC.equals("")) {
cellID = mCell1CI;
locationAreaCode = mCell1TAC;
} else if (mCell1CI.equals("") && mCell1TAC.equals("")) {
cellID = mCell1CID;
locationAreaCode = mCell1LAC;
} else {
Log.d("GeoL", "3");
}
String requestBody =
"{" +
"\"cellTowers\":[" +
"{" +
"\"cellId\" :" + cellID + "," +
"\"locationAreaCode\" :" + locationAreaCode + "," +
"\"mobileCountryCode\" :" + "\"" + mCell1MCC + "\"" + "," +
"\"mobileNetworkCode\" :" + "\"" + mCell1MNC + "\"" +
"}" +
"]" +
"}";
// Instantiate the RequestQueue.
RequestQueue queue = Volley.newRequestQueue(this);
JsonObjectRequest jsObjRequest = new JsonObjectRequest
(Request.Method.POST, url, requestBody, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
JSONObject jsonObject;
try {
jsonObject = new JSONObject(String.valueOf(response));
JSONObject latitude = jsonObject.getJSONObject("location");
String lat = latitude.getString("lat");
String lng = latitude.getString("lng");
String acc = jsonObject.getString("accuracy");
if (!dataReceived.listIterator().hasNext()){
String print;
print = String.format("%s%s", print, print(lat.toString(), lng.toString(), acc.toString()));
writeToFile(print, getApplicationContext());
} else {
String print;
print = String.format("%s%s,", print, print(lat.toString(), lng.toString(), acc.toString()));
writeToFile(print, getApplicationContext());
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e("Response", "error" + error.toString());
}
});
queue.add(jsObjRequest);
}
}
} catch (JSONException e) {
e.printStackTrace();
}
I need to concat the received value to the print variable.
But this the error which i receive
print needs to be initialized is what I receive.
also if declared outside the try/catch block it requires it to be final.
What to do?
just use String print = null; when you declare print
You are providing a value that is not initialized to the String.format
You need to initialize the variable "print" with what you want to be used in the String.format (for example an empty String) :
String print= ""
Or use String Builder:
StringBuilder stringBuilder = new StringBuilder();
stringBuilder.append("1");
stringBuilder.append("2");
String finalString = stringBuilder.toString();

How to get the results from multiple servers in a function in Android

I'm installing Hybrid Ranking algorithm for Linked Data Extraction & Context on Android. Documents you can search Google for the keywords above.
And now I'm installing semantic similarity between two uri1 and uri2.
Input: two DBpedia URIs
Output: a value representing their similarity
private float similarity(String uri1, String uri2) {
float wikipedia = wikiS(uri1, uri2);
float abtract = abtractS(uri1, uri2);
float google = engineS(uri1, uri2, google);
float yahoo = engineS(uri1, uri2, yahoo);
float bing = engineS(uri1, uri2, bing);
float dilicious = engineS(uri1, uri2, dilicicous);
return wikipedia + abtract + google + yahoo + bing + dilicious;
}
And with each child function, I have to query data using SPARQL dbpedia, google, yahoo, bing, dilicious using provided API. The results obtained will be calculated to the parser and returns the corresponding float value.
Example for abtractS(uri1, uri2) below:
private float abstractS(String uri1, String uri2, final float wikiS){
String url = createUrlAbstractS(uri1, uri2);
StringRequest request = new StringRequest(Request.Method.GET, url, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
float abtractS = 0.0f;
try {
JSONObject jsonObject = new JSONObject(response);
JSONArray data = jsonObject.getJSONObject("results").getJSONArray("bindings");
if(data.length() == 0){
showLogAndToast("No result");
}else{
JSONObject element = data.getJSONObject(0);
String label1 = element.getJSONObject("label1").getString("value");
String abtract1 = element.getJSONObject("abtract1").getString("value");
String label2 = element.getJSONObject("label2").getString("value");
String abtract2 = element.getJSONObject("abtract2").getString("value");
abtractS = calWordContained(label1, abtract2) + calWordContained(label2, abtract1) + wikiS;
//TODO: RESULT ABTRACTS HERE. How next?
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.d(TAG, error.getMessage());
}
});
AppController.getInstance().addToRequestQueue(request);
return 0.0f;//HERE: no results
}
private float calWordContained(String label, String abtract){
if(label.length() == 0 || abtract.length() == 0){
return 0.0f;
}
List<String> words = Arrays.asList(label.split(" "));
int count = 0;
float length = words.size();
for(int i = 0; i < length; i++){
if(abtract.toLowerCase().contains(words.get(i).toLowerCase())){
count++;
}
}
return (count/length);
}
public String createUrlAbstractS(String uri1, String uri2){
private String BASE_URL_DBPEDIA = "http://dbpedia.org/sparql?default-graph-uri=&query=";
String query = createQueryAbstractS(uri1, uri2);
String url = "";
try {
url = Config.BASE_URL_DBPEDIA + URLEncoder.encode(query, "UTF-8") + Config.RESULT_JSON_TYPE;
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
return url;
}
private String createQueryAbstractS(String uri1, String uri2){
String query = Config.PREFIX_DBPEDIA + " \n" +
"prefix dbpedia-owl: <http://dbpedia.org/ontology/>\n" +
"\n" +
"\n" +
"select ?label1, ?label2, ?abtract1, ?abtract2 where\n" +
"{\n" +
" {\n" +
" select *\n" +
" where{\n" +
" <" + uri1 + "> rdfs:label ?label1 ;\n" +
" dbpedia-owl:abstract ?abtract1 .\n" +
" FILTER langMatches(lang(?abtract1),'en') . \n" +
" FILTER langMatches(lang(?label1),'en') .\n" +
" }\n" +
" }\n" +
"\n" +
"\n" +
" {\n" +
" select *\n" +
" where{\n" +
" <" + uri2 + "> rdfs:label ?label2 ;\n" +
" dbpedia-owl:abstract ?abtract2 .\n" +
" FILTER langMatches(lang(?label2),'en') . \n" +
" FILTER langMatches(lang(?abtract2),'en') .\n" +
" }\n" +
" }\n" +
"}";
return query;
}
but how to do this on, I could not get the results I wanted in the similarity function (uri1, uri2). Therefore it will affect the results in different functions.
So I'm asking is: how can I get all the results of the function Wikis, abtractS, engine (google), engine (bing), engine (yahoo), engine (dilicious) in a simple way Best. I currently do on Android and data load times is very important.
Thank you very much!

Why the Views are not updated with JSON parsed information

I'm having Problem in updating JSON parsed informations in my Views. Nothing is problem with getting JSON text from internet it works fine. I hope parsing process also looks good. Im having problem with Displaying contents in the Views.
package rev.app.revlearningdemo;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URL;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.widget.TextView;
public class JsonFromInternet extends Activity {
String jsonText, name, weather_main, description, lon, lat, temp, pressure,
humidity, temp_min, temp_max, speed, deg;
long dt, sunrise, sunset;
TextView area, info, main;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.weather);
area = (TextView) findViewById(R.id.weatherAreaName);
info = (TextView) findViewById(R.id.weatherInfo);
main = (TextView) findViewById(R.id.weatherMain);
Thread net = new Thread() {
public void run() {
URL url;
BufferedReader buff = null;
StringBuilder build = new StringBuilder();
try {
url = new URL(
"http://api.openweathermap.org/data/2.5/weather?q=Madurai,in");
buff = new BufferedReader(new InputStreamReader(
url.openStream(), "UTF-8"));
for (String l; (l = buff.readLine()) != null;)
build.append(l.trim());
} catch (IOException e1) {
Log.e("REV DEMO", "ERROR");
} finally {
if (buff != null)
try {
buff.close();
} catch (IOException e) {
Log.e("REV DEMO", "ERROR");
}
jsonText = build.toString();
interrupt();
}
};
};
net.start();
if (net.getState()==Thread.State.TERMINATED) {
parseJsonText(jsonText);
area.setText(name);
info.setText(description + "\n" + "Longitude, Lattitude " + lon
+ ", " + lat + "\nTemperature " + temp + "\n(Min:"
+ temp_min + ", Max:" + temp_max + ")\nPressure "
+ pressure + "\nHumidity " + humidity + "\nWind Speed "
+ speed + ", direction " + deg);
main.setText(weather_main);
}
}
private void parseJsonText(String jsonFromInternet) {
JSONObject root, coord, main, wind, sys, weather;
try {
root = new JSONObject(jsonFromInternet);
coord = root.getJSONObject("coord");
lon = coord.optString("lon");
lat = coord.optString("lat");
main = root.getJSONObject("main");
temp = main.optString("temp");
pressure = main.optString("pressure");
humidity = main.optString("humidity");
temp_min = main.optString("temp_min");
temp_max = main.optString("temp_max");
wind = root.getJSONObject("wind");
speed = wind.optString("speed");
deg = wind.optString("deg");
sys = root.getJSONObject("sys");
sunrise = sys.optLong("sunrise");
sunset = sys.optLong("sunset");
dt = root.optLong("dt");
name = root.optString("name");
weather = root.optJSONArray("weather").getJSONObject(0);
weather_main = weather.optString("main");
description = weather.optString("description");
} catch (JSONException e) {
e.printStackTrace();
}
}
}
You start asynchronous Thread to download the JSON and it means that your views are getting updated immediately (when your jsonText is not initialized yet).
Move updating your views into the end of run() method and update your views when you finished parsing data, not earlier. Warning: to call setText from thread you will have to use runOnUiThread method.
Thread net = new Thread() {
public void run() {
URL url;
BufferedReader buff = null;
StringBuilder build = new StringBuilder();
try {
url = new URL(
"http://api.openweathermap.org/data/2.5/weather?q=Madurai,in");
buff = new BufferedReader(new InputStreamReader(
url.openStream(), "UTF-8"));
for (String l; (l = buff.readLine()) != null;)
build.append(l.trim());
// parse and update views now:
jsonText = build.toString();
parseJsonText(jsonText);
runOnUiThread(new Runnable() {
#Override
public void run() {
area.setText(name);
info.setText(description + "\n" + "Longitude, Lattitude " + lon
+ ", " + lat + "\nTemperature " + temp + "\n(Min:"
+ temp_min + ", Max:" + temp_max + ")\nPressure "
+ pressure + "\nHumidity " + humidity + "\nWind Speed "
+ speed + ", direction " + deg);
main.setText(weather_main);
}
});
} catch (IOException e1) {
Log.e("REV DEMO", "ERROR");
} finally {
if (buff != null)
try {
buff.close();
} catch (IOException e) {
Log.e("REV DEMO", "ERROR");
}
interrupt();
}
};
};

Remove previous route in graphhopper android?

I am using graphhopper and mapsforge to show the route in my android app.The route is shown in my mapView from the polyline but when I change the location of second point the new route is shown above the previous route.So I need to delete this previous route when a new route is calculated. The code is as follows:
GraphHopper localGraphHopper = new GraphHopper().forMobile();
localGraphHopper.setCHShortcuts(true, true);
localGraphHopper.load(getFolderPath());
GHRequest localGHRequest = new GHRequest(paramDouble1, paramDouble2, paramDouble3, paramDouble4);
GHRequest a = localGHRequest.setAlgorithm("dijkstrabi");
GHResponse localGHResponse = localGraphHopper.route(localGHRequest);
int i = localGHResponse.getPoints().getSize();
PointList localPointList = localGHResponse.getPoints();
Polyline localPolyline = new Polyline(createPaint(AndroidGraphicFactory.INSTANCE.createColor(Color.RED), 4, Style.STROKE), AndroidGraphicFactory.INSTANCE);
this.latLongs_track = localPolyline.getLatLongs();
for (int j = 0;; j++)
{
if (j >= i)
{
this.mapView.getLayerManager().getLayers().add(localPolyline);
LatLong localLatLong = new LatLong((paramDouble1 + paramDouble3) / 2.0D, (paramDouble2 + paramDouble4) / 2.0D);
this.mapView.getModel().mapViewPosition.setCenter(localLatLong);
return;
}
this.latLongs_track.add(new LatLong(localPointList.getLatitude(j), localPointList.getLongitude(j)));
}
Use this function:
public void calcPath( final double fromLat, final double fromLon,
final double toLat, final double toLon ) {
log("calculating path ...");
new AsyncTask<Void, Void, GHResponse>(){
float time;
protected GHResponse doInBackground( Void... v ){
StopWatch sw = new StopWatch().start();
GHRequest req = new GHRequest(fromLat, fromLon, toLat, toLon).
setAlgorithm(AlgorithmOptions.DIJKSTRA_BI);
req.getHints().
put("instructions", "false");
GHResponse resp = hopper.route(req);
time = sw.stop().getSeconds();
return resp;
}
protected void onPostExecute( GHResponse resp ){
if (!resp.hasErrors()){
log("from:" + fromLat + "," + fromLon + " to:" + toLat + ","
+ toLon + " found path with distance:" + resp.getDistance()
/ 1000f + ", nodes:" + resp.getPoints().getSize() + ", time:"
+ time + " " + resp.getDebugInfo());
logUser("the route is " + (int) (resp.getDistance() / 100) / 10f
+ "km long, time:" + resp.getMillis() / 60000f + "min, debug:" + time);
mapView.getLayerManager().getLayers().add(createPolyline(resp));
//mapView.redraw();
} else{
logUser("Error:" + resp.getErrors());
}
shortestPathRunning = false;
}
}.execute();
}
All source you can find at https://github.com/graphhopper/graphhopper
I have found the answer for my problem and am posting here
Polyline localPolyline;
public void calcPath( final double fromLat, final double fromLon,
final double toLat, final double toLon )
{
log("calculating path ...");
new AsyncTask<Void, Void, GHResponse>()
{
float time;
protected GHResponse doInBackground( Void... v )
{
StopWatch sw = new StopWatch().start();
GHRequest req = new GHRequest(fromLat, fromLon, toLat, toLon).
setAlgorithm(AlgorithmOptions.DIJKSTRA_BI);
req.getHints()
.put("instructions", "false");
GHResponse resp = hopper.route(req);
time = sw.stop().getSeconds();
return resp;
}
protected void onPostExecute( GHResponse resp )
{
if (!resp.hasErrors())
{
if(localPolyline!=null){
mapView.getLayerManager().getLayers().remove(localPolyline);
}
else{
log("here");
}
log("from:" + fromLat + "," + fromLon + " to:" + toLat + ","
+ toLon + " found path with distance:" + resp.getDistance()
/ 1000f + ", nodes:" + resp.getPoints().getSize() + ", time:"
+ time + " " + resp.getDebugInfo());
logUser("the route is " + (int) (resp.getDistance() / 100) / 10f
+ "km long, time:" + resp.getMillis() / 60000f + "min, debug:" + time);
localPolyline=createPolyline(resp);
mapView.getLayerManager().getLayers().add(localPolyline);
} else
{
logUser("Error:" + resp.getErrors());
}
}
}.execute();
}
Thanks to everybody.

Categories

Resources