I get a json data successfully from Twitter Rest Api. You can see the json data at following link.
https://dev.twitter.com/rest/reference/get/friends/list. I'm trying to do bind this friends list json data to my listview.I will bind username,profile picture etc.Note that there can be thousands of data.Is it a good practice binding all data or should i bind them like loading 10 datas.
MyTwitterApiClients apiclients = new MyTwitterApiClients(session);
apiclients.getFriendsListService().show(userID, userName, new Callback<Response>(){
#Override
public void success(Result<Response> result) {
BufferedReader reader = null;
StringBuilder sb = new StringBuilder();
try {
reader = new BufferedReader(new InputStreamReader(result.response.getBody().in()));
String line;
while ((line = reader.readLine()) != null) {
sb.append(line);
}
} catch (IOException e) {
e.printStackTrace();
}
String jsonResult = sb.toString();
try {
JSONObject objResult=new JSONObject(jsonResult);
///What should i do ?
} catch (JSONException e) {
e.printStackTrace();
}
}
I suggest you to have a look here: here you can find good examples on how to manage those kind of situations.
In a nutshell: if you're having hundreds/thousands of images to load, it's better if you don't load them all together, but only when you really need to show 'em
Related
So I have 45 geojson files and I would like that each of them would have a different color which works.The next task which I have set for myself is that when I click on a layer it would display the district it was assigned by. Yet that doesn't work it only displays the last number which is 45 and it doesn't matter how I assign it.
Android Google Maps GeoJsonLayer OnFeatureClickListener, multiple layers
A similar question has been already asked. But I didn't get the answer.
How would I create MultiPolygons? What are features?
Is it even possible to solve this task with a for loop or do I realy have to assign every by hand?
Also I imagine this task can be done with Polygons, can one get the latitude and longitude data from geojson files?
for(int i=1;i<=45; i++) {
String fileNameTemp = "a" + i + ".geojson";
try {
InputStream is = am.open(fileNameTemp);
BufferedReader br = new BufferedReader(new InputStreamReader(is));
StringBuilder sb = new StringBuilder();
String line = br.readLine();
while (line != null) {
sb.append(line);
line = br.readLine();
}
data = sb.toString();
} catch (IOException ex) {
ex.printStackTrace();
}
if (data == null) return;
JSONObject json = null;
try {
json = new JSONObject(data);
} catch (JSONException ex) {
ex.printStackTrace();
}
if (json == null) return;
GeoJsonLayer geoJsonLayer = new GeoJsonLayer(mMap, json);
GeoJsonPolygonStyle geoJsonPolygonStyle = geoJsonLayer.getDefaultPolygonStyle();
Random r = new Random();
int color = r.nextInt(0xFFFFFF);
int colorTransparent = ColorUtils.setAlphaComponent(color, 100);
geoJsonLayer.setOnFeatureClickListener(new Layer.OnFeatureClickListener() {
#Override
public void onFeatureClick(Feature feature) {
Log.d("district Nr.: ",i+"");
}
});
geoJsonPolygonStyle.setStrokeColor(0);
geoJsonPolygonStyle.setStrokeWidth(500);
geoJsonPolygonStyle.setFillColor(colorTransparent);
geoJsonLayer.addLayerToMap();
}
I have a file in my devise called test.csv. when i click on that file is opened through my app.how to set default open with(dialog) option to my app in android?
above is the sample dailog.how to add my app to the dialog list?
I think you may want to read the csv file. you could get the csv file path. So see the following.
public static void readCSV(File file) {
BufferedReader reader = null;
StringBuilder stringBuilder = new StringBuilder();
try {
InputStreamReader isr = new InputStreamReader(new FileInputStream(file));// your csv file
reader = new BufferedReader(isr);
String line = null; // every time read one line
while ((line = reader.readLine()) != null) {
stringBuilder.append(line);
stringBuilder.append("\n");
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
The stringBuilder.toString() is your csv file's content. Sorry for my English.
I can't figure out how to make this code work in an AsyncTask, I searched for multiple examples but it keeps crashing. I found this simple code on the internet and I want to adapt it to get the URL from a textfield and get the HTML code. I found out it has to be in an AsyncTask otherwise it won't work but even in an AsyncTask I can't get it to work. Here's my code:
String ETURL = ETURLInput.getText().toString();
try {
URL TestURL = new URL(ETURL);
BufferedReader bufferReader = new BufferedReader(
new InputStreamReader(TestURL.openStream()));
String outputCode;
while ((outputCode = bufferReader.readLine()) != null)
TVCode.setText(outputCode);
bufferReader.close();
} catch (Exception e) {
TVCode.setText("Oops, something went wrong.")
}
}
This is the code which needs to be executed inside an ActionListener. So when I click the button it should execute this code in an AsyncTask.
Hopefully somebody could help me with this.
You forgot to add openConnection, add this: URLConnection conn = TestURL.openConnection(); after creating your URL object.
To make it work with an asynctask, what you can do is storing your string in a class variable, returning it in the doInBackGround and using it in your onPostExecute.
An example of method you can create in your asynctask:
protected String getContentUrl(String URL) {
String line=null;
String result="";
try {
try {
URL url;
// get URL content
url = new URL(URL);
URLConnection conn = url.openConnection();
// open the stream and put it into BufferedReader
BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream()));
line=br.readLine();
while (line!= null) {
result=result+line;
line=br.readLine();
}
//System.out.print(result);
br.close();
return result;
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
} catch (Exception e) {
e.printStackTrace();
}
return null;
Then you get your result this way on doInBackGround:
getContentUrl(YOUR URL HERE)
Store this value in a String, and return it. Then you can use it in your onPostExecute
Hope it helps :)
I'm learning android by working on a simple project. I have the layout completed and I'm at a point where I need to communicate with the back-end. I've worked with PHP/JSON a lot before and I know exactly what I need to do on the back-end. I have the following two questions,
1 - What kind of adapter I should be using when dealing with JSON? please note that the back-end will be sending 10 records at a time, and the user will scroll up to get the next 10 so the dataset will be changing as the user scrolls the view
2 - I'll be using HTTP to get the JSON data mentioned in point 1, is there a preferred method in android to be used for communication with the back-end?
Please note that I don't want to Parse or any other cloud solutions.
1. You will have to have a something which will communicate with the server for that just copy this code :-
public class ConnectionClass
{
Context context;
public ConnectionClass(Context ctx) {
this.context=ctx;
}
public String connectToServer(String urlLink)
{
try
{
HttpClient client = new DefaultHttpClient();
HttpPost http_get = new HttpPost(urlLink);
HttpResponse responses;
responses = client.execute(http_get);
if (responses != null)
{
InputStream in = responses.getEntity().getContent();
String a = convertStreamToString(in);
return a;
}
}
catch (Exception e)
{
e.printStackTrace();
}
return null;
}
String convertStreamToString(InputStream is) {
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
StringBuilder sb = new StringBuilder();
String line = null;
try
{
while ((line = reader.readLine()) != null)
{
sb.append(line);
}
}
catch (Exception e)
{
//Toast.makeText(context, e.toString()+" io2", Toast.LENGTH_LONG).show();
}
finally
{
try
{
is.close();
}
catch (Exception e)
{
}
}
return sb.toString();
}
}
2. To use that and keeping in mind dat newer version of android does not allow executing network operations on mainthread i will give a simple example to run on onCreate() of the activity using AsyncTask this is something like Ajax in web .
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
context=this;
ConnectionClass cc=new ConnectionClass(context);
new AsyncTask<String, Void, String>()
{
#Override
protected String doInBackground(String... arg) {
String data=cc.connectToServer(arg[0]);
return data;
}
protected void onPostExecute(String result)
{
super.onPostExecute(result);
try
{
JSONObject jobj=new JSONObject(result);
String idval=jobj.getString("id");
Toast.makeToast(context,idval,2000).show();
} catch (Exception e)
{
e.printStackTrace();
}
}
}.execute("http://mydomain.com/fetchjson.php");
}
Android has built-in JSON parsing capability and an Http client. Take a look at this stackoverflow post, which has step-by-step instructions for making the Http request and parsing the returned JSON data:
How to parse JSON in Android
However, this post uses the older DefaultHttpClient. This is only recommended for Froyo and below. For newer code, Google recommends that you use HttpURLConnection instead (on Gingerbread and higher API systems). Their function is very similar, here is the reference for Android's HttpURLConnection:
HttpURLConnection | Android Developers
I have a android application, where i extract data from the multiple urls and save then as arraylist of string. It works fine, but for fetching data from 13 urls, it takes close to 15-20 sec. Where as fetching the data from same set of urls take 3-4 sec in same app built using phonegap. Here is the code below.
#Override
protected String doInBackground(String... params) {
client = new DefaultHttpClient();
for(int i=0;i<url.size();i++)
{
get = new HttpGet(url.get(i));
try {
response = client.execute(get);
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
entity = response.getEntity();
InputStream is = null;
try {
is = entity.getContent();
} catch (IllegalStateException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
BufferedReader reader = new BufferedReader(
new InputStreamReader(is));
StringBuffer buffer = new StringBuffer();
String line = null;
do {
try {
line = reader.readLine();
} catch (IOException e) {
e.printStackTrace();
}
buffer.append(line);
} while (line != null);
String str = buffer.toString();
param.add(str);
}
return null;
}
Could anyone please suggest how i can speed this execution and reduce the extraction time.
You could try starting a separate thread for each iteration from the for loop.
Smth like this :
for(int i = 0; i < url.size(); i++){
//start thread that gets data from url and adds it to the list
}