I'm trying to read a very heavy JSON (over than 6000 objects) and store them on a hash map to insert it into my database later.
But the problem is that I face with OOM and that's cause from my heavy JSON, however GSON library should rid me from this situation, but it is not !!!
Any ideas?
public Map<String,String> readJsonStream(InputStream in) throws IOException
{
JsonReader reader = new JsonReader(new InputStreamReader(in, "UTF-8"));
Map<String,String> contentMap = new HashMap<String,String>();
Gson mGson = new Gson();
contentMap = mGson.fromJson(reader, contentMap.getClass());
reader.close();
return contentMap;
}
From my experience, yes you can use google GSON to stream JSON data this is an example how to do it :
APIModel result = new APIModel();
try {
HttpResponse response;
HttpClient myClient = new DefaultHttpClient();
HttpPost myConnection = new HttpPost(APIParam.API_001_PRESENT(
serial_id, api_key));
try {
response = myClient.execute(myConnection);
Reader streamReader = new InputStreamReader(response
.getEntity().getContent());
JsonReader reader = new JsonReader(streamReader);
reader.beginObject();
while (reader.hasNext()) {
String name = reader.nextName();
if (name.equals("result")) {
if (reader.nextString() == "NG") {
result.setResult(Util.API_001_RESULT_NG);
break;
}
} else if (name.equals("items")) {
result = readItemsArray(reader);
} else {
reader.skipValue(); // avoid some unhandle events
}
}
reader.endObject();
reader.close();
} catch (Exception e) {
e.printStackTrace();
result.setResult(Util.API_001_RESULT_NG);
}
} catch (Exception e) {
e.printStackTrace();
result.setResult(Util.API_001_RESULT_NG);
}
readItemsArray function :
// read items array
private APIModel readItemsArray(JsonReader reader) throws IOException {
APIModel result = new APIModel();
String item_name, file_name, data;
result.setResult(Util.API_001_RESULT_OK);
reader.beginArray();
while (reader.hasNext()) {
item_name = "";
file_name = "";
data = "";
reader.beginObject();
while (reader.hasNext()) {
String name = reader.nextName();
if (name.equals("name")) {
item_name = reader.nextString();
} else if (name.equals("file")) {
file_name = reader.nextString();
} else if (name.equals("data")) {
data = reader.nextString();
} else {
reader.skipValue();
}
}
reader.endObject();
result.populateModel("null", item_name, file_name, data);
}
reader.endArray();
return result;
}
API Model Class :
public class APIModel {
private int result;
private String error_title;
private String error_message;
private ArrayList<String> type;
private ArrayList<String> item_name;
private ArrayList<String> file_name;
private ArrayList<String> data;
public APIModel() {
result = -1;
error_title = "";
error_message = "";
setType(new ArrayList<String>());
setItem_name(new ArrayList<String>());
setFile_name(new ArrayList<String>());
setData(new ArrayList<String>());
}
public void populateModel(String type, String item_name, String file_name, String data) {
this.type.add(type);
this.item_name.add(item_name);
this.file_name.add(file_name);
this.data.add(data);
}
public int getResult() {
return result;
}
public void setResult(int result) {
this.result = result;
}
public String getError_title() {
return error_title;
}
public void setError_title(String error_title) {
this.error_title = error_title;
}
public String getError_message() {
return error_message;
}
public void setError_message(String error_message) {
this.error_message = error_message;
}
public ArrayList<String> getType() {
return type;
}
public void setType(ArrayList<String> type) {
this.type = type;
}
public ArrayList<String> getItem_name() {
return item_name;
}
public void setItem_name(ArrayList<String> item_name) {
this.item_name = item_name;
}
public ArrayList<String> getFile_name() {
return file_name;
}
public void setFile_name(ArrayList<String> file_name) {
this.file_name = file_name;
}
public ArrayList<String> getData() {
return data;
}
public void setData(ArrayList<String> data) {
this.data = data;
}
}
before I use the streaming API from google GSON I also got OOM error because the JSON data I got is very big data (many images and sounds in Base64 encoding) but with GSON streaming I can overcome that error because it reads the data per token not all at once. And for Jackson JSON library I think it also have streaming API and how to use it almost same with my implementation with google GSON. I hope my answer can help you and if you have another question about my answer feel free to ask in the comment :)
Related
I am coding a Discord Giveaway Bot with Java. I am saving all the details of the Giveaway to a JSON file. Now I want to read the entries list and if the Users ID is not in the list I want to add it and save the file.
Here is the Giveaway Class:
public class Giveaway {
private String prize;
private long time;
private Integer winners;
private List<String> entries;
public Giveaway(String prize, Integer winners, long time, List<String> entries) {
this.prize = prize;
this.winners = winners;
this.time = time;
this.entries = entries;
}
public Giveaway() {}
public String getPrize() {
return prize;
}
public void setPrize(String prize) {
this.prize = prize;
}
public long getTime() {
return time;
}
public void setTime(long time) {
this.time = time;
}
public Integer getWinners() {
return winners;
}
public void setWinners(Integer winners) {
this.winners = winners;
}
public List<String> getEntries() {
return entries;
}
public void setEntries(List<String> entries) {
this.entries = entries;
}
}
When the GW is created the JSON looks like this:
{
"prize": "Discord Nitro",
"time": 1641732935,
"winners": 2,
"entries": []
}
Then when the user clicks a button it should read the list look if the ID is in the list and if not add the id. But when I save the list the whole JSON file changes.
How I read it out and save it:
public class ButtonClick extends ListenerAdapter {
private static Reader reader;
private static Giveaway giveaway = new Giveaway();
public void onButtonClick(ButtonClickEvent event) {
event.deferEdit().queue();
try {
reader = Files.newBufferedReader(Path.of(GiveawayStats.getGiveawayStats().getAbsolutePath()));
} catch (IOException e) {
e.printStackTrace();
}
if (event.getButton().getId().equals("gwEnter")) {
JsonParser parser = new JsonParser();
JsonObject obj = parser.parse(reader).getAsJsonObject();
JsonArray jsonEntries = obj.get("entries").getAsJsonArray();
long time = obj.get("time").getAsLong();
List<String> entries = new ArrayList<>();
for (JsonElement entrie : jsonEntries) {
entries.add(entrie.toString());
}
if (entries.contains(event.getMember().getId())) {
event.getChannel().sendMessage("Already in!").queue();
} else {
entries.add(event.getUser().getId().strip());
printToJson(entries);
}
}
try {
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
private static void printToJson(List<String> entries) {
GsonBuilder gsonBuilder = new GsonBuilder();
gsonBuilder.setVersion(2.0);
Gson gson = gsonBuilder.setPrettyPrinting().create();
giveaway.setEntries(entries);
try (Writer writer = new FileWriter(GiveawayStats.getGiveawayStats().getPath())) {
gson.toJson(giveaway, writer);
} catch (IOException e) {
e.printStackTrace();
}
}
}
After the print so JSON the file looks like this:
{
"time": 0,
"entries": [
"695629580014321747"
]
}
And when I click the Button again it looks like this:
{
"time": 0,
"entries": [
"\"695629580014321747\"",
"695629580014321747"
]
}
So why is my IF condition not working?
You are using entrie.toString() which gives you the string that is used for console output. You should be using entrie.getAsString() instead.
Furthermore, you are also using a lot of deprecated things with JsonParser which should be replaced. new JsonParser().parse(...) should be replaced by JsonParser.parseReader(...).
Above all that, it is highly recommended using a database for this kind of task. Something such as SQLite or Redis would be much better at handling concurrent changes and redundancy. Or at least, you should use a try-with-resources for your reader.
try (Reader reader = ...) {
JsonElement json = JsonParser.parseReader(reader).getAsJsonObject();
...
}
I'm trying to check if config1 exists in a text file, I'm using Google's Gson library.
My JSON file :
{
"maps":{
"config2":{
"component1":"url1",
"component2":"url1",
"component3":"url1"
},
"config1":{
"component1":"url1",
"component2":"url1",
"component3":"url1"
}
}
}
Loading :
public void load() throws IOException {
File file = getContext().getFileStreamPath("jsonfile.txt");
FileInputStream fis = getContext().openFileInput("jsonfile.txt");
InputStreamReader isr = new InputStreamReader(fis);
BufferedReader bufferedReader = new BufferedReader(isr);
StringBuilder sb = new StringBuilder();
String line;
while ((line = bufferedReader.readLine()) != null) {
sb.append(line);
}
String json = sb.toString();
Gson gson = new Gson();
Data data = gson.fromJson(json, Data.class);
componentURL= data.getMap().get("config1").get("component1");
Saving :
Gson gson = new Gson();
webViewActivity.Data data = gson.fromJson(json, webViewActivity.Data.class);
Map<String, String> configTest = data.getMap().get("config1");
data.getMap().get("config1").put(component, itemUrl);
String json = gson.toJson(data);
String filename = "jsonfile.txt";
FileOutputStream outputStream;
try {
outputStream = openFileOutput(filename, Context.MODE_PRIVATE);
outputStream.write(json.getBytes());
outputStream.close();
} catch (Exception e) {
e.printStackTrace();
}
Data class :
public class Data {
private Map<String, Map<String, String>> map;
public Data() {
}
public Data(Map<String, Map<String, String>> map) {
this.map = map;
}
public Map<String, Map<String, String>> getMap() {
return map;
}
public void setMap(Map<String, Map<String, String>> map) {
this.map = map;
}
}
My problem is that I need to create the file once and then check if the file exists, if it does I need to check if config1 exists if it doesn't I need to put config1 in the file.
But I can't check if config1 exists because I get :
java.lang.NullPointerException: Attempt to invoke virtual method 'java.util.Map com.a.app.ui.app.appFragment$Data.getMap()
I check if it exists by doing :
Boolean configTest = data.getMap().containsKey("config1");
if(!configTest){}
How can I create the file and check the data without getting a NullPointerException ?
I think you should modify the way you're handling things.
First create POJO for Config1 each values as:
// file Config1.java
public class Config1
{
private String component1;
private String component2;
private String component3;
public String getComponent1 ()
{
return component1;
}
public void setComponent1 (String component1)
{
this.component1 = component1;
}
public String getComponent2 ()
{
return component2;
}
public void setComponent2 (String component2)
{
this.component2 = component2;
}
public String getComponent3 ()
{
return component3;
}
public void setComponent3 (String component3)
{
this.component3 = component3;
}
#Override
public String toString()
{
return "ClassPojo [component1 = "+component1+", component2 = "+component2+", component3 = "+component3+"]";
}
}
And then after that POJO for Config2
// file Config2.java
public class Config2
{
private String component1;
private String component2;
private String component3;
public String getComponent1 ()
{
return component1;
}
public void setComponent1 (String component1)
{
this.component1 = component1;
}
public String getComponent2 ()
{
return component2;
}
public void setComponent2 (String component2)
{
this.component2 = component2;
}
public String getComponent3 ()
{
return component3;
}
public void setComponent3 (String component3)
{
this.component3 = component3;
}
#Override
public String toString()
{
return "ClassPojo [component1 = "+component1+", component2 = "+component2+", component3 = "+component3+"]";
}
}
And then you need POJO for Maps
// file Maps.java
public class Maps
{
private Config2 config2;
private Config1 config1;
public Config2 getConfig2 ()
{
return config2;
}
public void setConfig2 (Config2 config2)
{
this.config2 = config2;
}
public Config1 getConfig1 ()
{
return config1;
}
public void setConfig1 (Config1 config1)
{
this.config1 = config1;
}
#Override
public String toString()
{
return "ClassPojo [config2 = "+config2+", config1 = "+config1+"]";
}
}
And finally the class which will wrap everything up MyJsonPojo. Though you can rename it to whatever you want.
// file MyJsonPojo.java
public class MyJsonPojo
{
private Maps maps;
public Maps getMaps ()
{
return maps;
}
public void setMaps (Maps maps)
{
this.maps = maps;
}
#Override
public String toString()
{
return "ClassPojo [maps = "+maps+"]";
}
}
Finally replace your code in the loadData() method as:
public void load() throws IOException {
File file = getContext().getFileStreamPath("jsonfile.txt");
FileInputStream fis = getContext().openFileInput("jsonfile.txt");
InputStreamReader isr = new InputStreamReader(fis);
BufferedReader bufferedReader = new BufferedReader(isr);
StringBuilder sb = new StringBuilder();
String line;
while ((line = bufferedReader.readLine()) != null) {
sb.append(line);
}
String json = sb.toString();
Gson gson = new Gson();
Data data = gson.fromJson(json, MyJsonPojo.class);
Maps maps = data.getMaps();
Config1 config1 = null;
if (maps != null) {
config1 = maps.getConfig1()
}
if (config1 != null) {
componentURL = config1.getComponent1();
}
}
For saving the values you can do this:
public void save() {
// set url here
Component1 component1 = new Component1();
component1.setComponent1(itemUrl);
// store it in maps
Maps maps = new Maps();
maps.setComponent1(component1);
// finally add it to the MyJsonPojo instance
MyJsonPojo myJsonPojo = new MyJsonPojo();
myJsonPojo.setMaps(maps);
Gson gson = new Gson();
String json = gson.toJson(maps);
String filename = "jsonfile.txt";
FileOutputStream outputStream;
try {
outputStream = openFileOutput(filename, Context.MODE_PRIVATE);
outputStream.write(json.getBytes());
outputStream.close();
} catch (Exception e) {
e.printStackTrace();
}
}
Please note that you may have to modify the save() code as per your structure because I am quite unsure about how you have handled what in the code. I have provided the basic implementation without much proof reading my code.
So I was following this tutorial and it has this method.
new AsyncTask<Void,Void,Void>(){
#Override
protected Void doInBackground(Void... voids) {
Reader reader=API.getData("http://beta.json-generator.com/api/json/get/DiIRBM4");
Type listType = new TypeToken<ArrayList<DoctorBean>>(){}.getType();
beanPostArrayList = new GsonBuilder().create().fromJson(reader, listType);
postList=new StringBuffer();
for(DoctorBean post: beanPostArrayList){
postList.append("\n heroName: "+post.getHeroName()+"\n realName: "+post.getRealName()+"\n\n");
}
return null;
}
#Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
Log.d("JSON Result ", postList.toString());
}
}.execute();
The Log Result would only show these values.
JSON Result:
heroName: null realName: null
heroName: null realName: null
heroName: null realName: null
This is my JSON data
[
{
"heroName": "Dr. Strange",
"realName": "Stephen Strange"
},
{
"heroName": "Spider-Man",
"realName": "Peter Paker"
},
{
"heroName": "Captain America",
"realName": "Stever Rogers"
}
]
This is my Data Model
import com.google.gson.annotations.SerializedName;
public class DoctorBean {
#SerializedName("heroName")
private String heroName;
#SerializedName("realName")
private String realName;
public DoctorBean(String heroName, String realName) {
this.heroName = heroName;
this.realName = realName;
}
public String getHeroName() {
return heroName;
}
public void setHeroName(String heroName) {
this.heroName = heroName;
}
public String getRealName() {
return realName;
}
public void setRealName(String realName) {
this.realName = realName;
}
}
And this is my API class
public class API {
private static Reader reader=null;
public static Reader getData(String SERVER_URL) {
try {
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(SERVER_URL);
HttpResponse response = httpClient.execute(httpPost);
StatusLine statusLine = response.getStatusLine();
if (statusLine.getStatusCode() == 200) {
HttpEntity entity = response.getEntity();
InputStream content = entity.getContent();
reader = new InputStreamReader(content);
} else {
// Log.e("error:", "Server responded with status code: "+ statusLine.getStatusCode());
}
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IllegalStateException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return reader;
}
}
I noticed that the log Result showed 3 rows, so I was thinking it was able to get the length of the array correctly. But as for the data, all was null.
As per your given tutorial,from this link response is as below:
[
{
"date":"11/8/2014",
"auther":"nirav kalola",
"description":"json object parsing using gson library is easy",
"post_name":"json object parsing"
},
{
"date":"12/8/2014",
"auther":"nirav kalola",
"description":"json array parsing using gson library",
"post_name":"json array parsing"
},
{
"date":"17/8/2014",
"auther":"nirav kalola",
"description":"store json file in assets folder and get data when required",
"post_name":"json parsing from assets folder"
}
]
So you need to try below POJO class for GSONBuilder. Replace your name with BeanPost.
import com.google.gson.annotations.SerializedName;
public class BeanPost {
#SerializedName("post_name")
private String post_name;
#SerializedName("auther")
private String auther;
#SerializedName("date")
private String date;
#SerializedName("description")
private String description;
public BeanPost(String post_name, String auther, String date, String description) {
this.post_name = post_name;
this.auther = auther;
this.date = date;
this.description = description;
}
public String getPost_name() {
return post_name;
}
public void setPost_name(String post_name) {
this.post_name = post_name;
}
public String getAuther() {
return auther;
}
public void setAuther(String auther) {
this.auther = auther;
}
public String getDate() {
return date;
}
public void setDate(String date) {
this.date = date;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
}
Try to create beanPostArrayList as above pojo class arraylist. And try your code and get appropriate fields from it.
I hope its helps you.
Try this.
Create an array from response :
DoctorBean[] doctorBeanArray = new Gson().fromJson(response, DoctorBean[].class); // Where response is your string response
Then create an ArrayList :
ArrayList<DoctorBean> doctorBeanList = new ArrayList<DoctorBean>(Arrays.asList(doctorBeanArray));
I am working on a project to get into android development, having some knowledge of java before I am thinking of reading data from a text file, which will be formatted like this;
Type: House
Image link: www.bit.ly/image1
Name: Black
Download Link: www.bit.ly/image1download
----------
Type: Car
Image link: www.bit.ly/image2
Name: yellow
Download Link: www.bit.ly/image2download
----------
Type: Backyard
Image link: www.bit.ly/image3
Name: Green
Download Link: www.bit.ly/image3download
----------
Type: Window
Image link: www.bit.ly/image4
Name: Solid
Download Link: www.bit.ly/image4download
----------
Type: Table
Image link: www.bit.ly/image5
Name: Brown
Download Link: www.bit.ly/image5download
----------
The data contains 4 pieces of information per set, Type, Image, Name and Download. I need a way of reading this and saving/writing it to a arraylist which I then can display in a listview that I will have on my app. (I am currently looking at tutorials on creating listview, if you know any useful tutorials please let me know)
Arraylist <String> data = new ArrayList<String>();
Data.add(“House”,” www.bit.ly/image1”,”black”,”www.bit.ly/image1download”);
Data.add(“Car”,” www.bit.ly/image2”,”yellow”,” www.bit.ly/image2download”);
……..
……..
In reality there will be a lot more data then just 5 sets , so I want to use for loop to loop through each data data and add it to the data arraylist.
I am not sure how I can approach this, any help is welcomed, I am really stuck. Please let me know if I have not explained my question properly.
EDITED:
Would this be the correct way of reading data from a textfile?
Scanner content = new Scanner(new File("Data.txt"));
ArrayList<String> data = new ArrayList<String>();
while (content.hasNext()){
data.add(content.next());
}
content.close();
Or is this another way in android
Before start go through this link for reading
How can I read a text file in Android?
Use PoJo Models for your needs,
Create a PoJo class like this
public class Film {
private String filmName;
private String mainStar;
public String getFilmName() {
return filmName;
}
public void setFilmName(String filmName) {
this.filmName = filmName;
}
public String getMainStar() {
return mainStar;
}
public void setMainStar(String mainStar) {
this.mainStar = mainStar;
}
}
Create ArrayList
private ArrayList<Film > filmArray=new ArrayList<Film>();
Store Each arraylist with instance of your PoJo class like this
for(int i=0;i<sizei++)
{
Film film=new Film();
film.setFilmName("your value");
film.setMainStar("your value");
filmArray.add(film);
}
and then access list of values in arraylist of PoJo class in filmArray list.
Simple and elegant solution.
Here is the parser
public class FileParser {
private static final String DATA_TERMINATION = "----------";
private static final String TYPE="Type";
private static final String IMAGE="Image link";
private static final String NAME= "Name";
private static final String DWNLD_LNK= "Download Link";
public static void main(String[] args) {
FileParser parser = new FileParser();
try {
for(Data d:parser.parseDataFile(new File("F:\\data.txt"))){
System.out.println(TYPE+":"+d.getType());
System.out.println(IMAGE+":"+d.getImage());
System.out.println(NAME+":"+d.getName());
System.out.println(DWNLD_LNK+":"+d.getLink());
System.out.println(DATA_TERMINATION);
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public List<Data> parseDataFile(File input) throws Exception{
List<Data> output =null;
List<String> fileOp= null;
try {
validateInput(input);
fileOp = readFile(input);
output = parseData(fileOp);
} catch (Exception e) {
throw e;
}
return output;
}
private List<Data> parseData(List<String> fileOp) {
List<Data> output =null;
output = new ArrayList<Data>();
Data data;
data = new Data();
for(String line:fileOp){
if(DATA_TERMINATION.equalsIgnoreCase(line)){
output.add(data);
data = new Data();
}else{
parseField(data,line);
}
}
return output;
}
private void parseField(Data data, String line) {
StringTokenizer tokenzr = new StringTokenizer(line,":");
if(tokenzr.countTokens() !=2){
System.out.println("Cant parse line"+line);
}else{
switch (tokenzr.nextToken()) {
case TYPE:
data.setType(tokenzr.nextToken());
break;
case IMAGE:
data.setImage(tokenzr.nextToken());
break;
case NAME:
data.setName(tokenzr.nextToken());
break;
case DWNLD_LNK:
data.setLink(tokenzr.nextToken());
break;
default:
break;
}
}
}
private List<String> readFile(File input) throws Exception {
BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream(input)));
String line = null;
List<String> op = new ArrayList<String>();
try {
while((line = reader.readLine()) != null){
op.add(line);
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
throw e;
}
return op;
}
private void validateInput(File input) throws Exception {
if(input == null){
throw new Exception("Null input");
}else if(!input.exists() || !input.isFile() || !input.canRead() ) {
throw new Exception("File not readable");
}
}
}
Do this way define a setter getter class to hold and return values like this :
Data.class
public class Data {
String type,Image,Name,Link ;
public Data() {
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public String getImage() {
return Image;
}
public void setImage(String image) {
Image = image;
}
public String getName() {
return Name;
}
public void setName(String name) {
Name = name;
}
public String getLink() {
return Link;
}
public void setLink(String link) {
Link = link;
}
}
using for loop set data in a arraylist
Arraylist <Data> arrayListData = new ArrayList<Data>();
for(int i=0;i<arrayListData .size();i++){
Data data=new Data();
data.setType("");
...
...
...
arrayListData.add(data);
}
and to fetch data from arraylist
String type= arrayListData.get(position).getType();
Updated :
read .txt file like this , I am assuming your text file is saved in sdcard of device :
public void readfile() {
StringBuilder text = new StringBuilder();
File sdcard = Environment.getExternalStorageDirectory();
ArrayList<Data> arrayList=new ArrayList<Data>();
//Get the text file
File file = new File(sdcard,"textfile.txt");
//Read text from file
try {
BufferedReader br = new BufferedReader(new FileReader(file));
String line;
Data data=new Data();
while ((line = br.readLine()) != null) {
text.append(line);
text.append('\n');
if(line.contains(":")){
int index=line.indexOf(":");
String s=line.substring(index+1).trim();
if(line.contains("Type")){
data.setType(s);
}
if(line.contains("Image")){
data.setImage(s);
}
if(line.contains("Name")){
data.setName(s);
}
if(line.contains("Download")){
data.setLink(s);
}
}
if(line.contains("-")){
arrayList.add(data);
data=new Data();
}
}
System.out.println(text);
br.close();
}
catch (IOException e) {
e.printStackTrace();
}
}
I am building a taxi app similar to Uber.. I am using Android Studio and implementing code in Java. Java servlets and jsps for the server side with My sql as the DB.
Any links or code with my mentioned requirement would be of great help.
I want a search bar with suggestions with a drop down menu of pickup and drop off locations like the one in Uber app.?
Thanks in advance.
Create new activity and get input from user or use static input in order to query from google for nearby places
StringBuilder sb = new StringBuilder("https://maps.googleapis.com/maps/api/place/textsearch/json?");
sb.append("query=" + "Your input OR user input";
sb.append("&key=You Api key here");
PlacesTask placesTask = new PlacesTask();
placesTask.execute(sb.toString());
and create a PlacesTask class
private class PlacesTask extends AsyncTask<String, Integer, String> {
String data = null;
#Override
protected String doInBackground(String... url) {
try {
data = downloadUrl(url[0]);
} catch (Exception e) {
Log.d("Background Task", e.toString());
}
return data;
}
#Override
protected void onPostExecute(String result) {
ParserTask parserTask = new ParserTask();
parserTask.execute(result);
}
}
private String downloadUrl(String strUrl) throws IOException {
String data = "";
InputStream iStream = null;
HttpURLConnection urlConnection = null;
try {
URL url = new URL(strUrl);
urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.connect();
iStream = urlConnection.getInputStream();
BufferedReader br = new BufferedReader(new InputStreamReader(iStream));
StringBuffer sb = new StringBuffer();
String line = "";
while ((line = br.readLine()) != null) {
sb.append(line);
}
data = sb.toString();
br.close();
} catch (Exception e) {
Log.d("Exception url", e.toString());
} finally {
iStream.close();
urlConnection.disconnect();
}
return data;
}
And then create Paresetask
private class ParserTask extends AsyncTask<String, Integer, List<HashMap<String, String>>> {
JSONObject jObject;
#Override
protected List<HashMap<String, String>> doInBackground(String... jsonData) {
List<HashMap<String, String>> places = null;
PlacesJSONParser placeJsonParser = new PlacesJSONParser();
try {
jObject = new JSONObject(jsonData[0]);
places = placeJsonParser.parse(jObject);
} catch (Exception e) {
Log.d("Exception", e.toString());
}
return places;
}
// Executed after the complete execution of doInBackground() method
#Override
protected void onPostExecute(List<HashMap<String, String>> list) {
if (customSearch) {
if (list.size() == 0) {
placesList.setVisibility(View.GONE);
error_text.setVisibility(View.VISIBLE);
error_text.setTextColor(getResources().getColor(R.color.error_message_color));
} else {
placesList.setVisibility(View.VISIBLE);
error_text.setVisibility(View.GONE);
}
mPlaceArrayList = new ArrayList<>();
mAdapter = new PlaceListAdapter(NearByPlaces.this, mPlaceArrayList, true);
placesList.setAdapter(mAdapter);
}
for (int i = 0; i < list.size(); i++) {
mNearByPlace = new NearByPlace();
HashMap<String, String> hmPlace = list.get(i);
mNearByPlace.setLatitude(hmPlace.get("lat"));
mNearByPlace.setLongitude(hmPlace.get("lng"));
mNearByPlace.setName(hmPlace.get("place_name"));
mNearByPlace.setVicinity(hmPlace.get("vicinity"));
mPlaceArrayList.add(mNearByPlace);
}
mAdapter.setPlaceArrayList(mPlaceArrayList);
}
}
and NearByPlace is
public class NearByPlace {
private String name;
private String address;
private String latitude;
private String longitude;
private String vicinity;
private String placeIcon;
public NearByPlace(){}
public String getPlaceIcon() {
return placeIcon;
}
public void setPlaceIcon(String placeIcon) {
this.placeIcon = placeIcon;
}
public String getVicinity() {
return vicinity;
}
public void setVicinity(String vicinity) {
this.vicinity = vicinity;
}
public String getLongitude() {
return longitude;
}
public void setLongitude(String longitude) {
this.longitude = longitude;
}
public String getLatitude() {
return latitude;
}
public void setLatitude(String latitude) {
this.latitude = latitude;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
Hope it will help you and you can resolve the minor errors in coz i copied and pasted code from one of my project..