How to parse json from asset folder to listview? - android

I want to parse text and image from a json on file in asset folder to my listview. Please explain clearly because I am biginner in android. Give me complete codes of all files. Thank you a lot.

Just open the file from the assets folder like this
StringBuilder buf=new StringBuilder();
InputStream json;
try {
json = context.getAssets().open("YOUR_FILE_NAME.txt");
BufferedReader in=
new BufferedReader(new InputStreamReader(json, "UTF-8"));
String str;
while ((str=in.readLine()) != null) {
buf.append(str);
}
}
catch (IOException e1) {
e1.printStackTrace();
}
result1 = buf.toString();
result1 will have the complete json from your file
then use this library called Gson to parse the json ...
Here is the tutorial for it Json parsing through Gson

Maybe code can help you.
public class MainActivity extends Activity {
private ListView listView;
private void log(String msg) {
Log.d("DNB", this.getClass().getName() + ">>" + msg);
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.listView = new ListView(this);
String jsonData = loadJsonFromAsset();
String[] items = parseJson(jsonData);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, items);
listView.setAdapter(adapter);
setContentView(listView);
log("json from asset: " + jsonData);
}
private String[] parseJson(String jsonData) {
String[] items = new String[0];
if (jsonData != null) {
try {
JSONArray jsonArray = new JSONArray(jsonData);
if (jsonArray != null) {
items = new String[jsonArray.length()];
for (int i = 0; i < items.length; i++) {
items[i] = jsonArray.get(i).toString();
}
}
} catch (JSONException e) {
log("err--" + e.toString());
}
}
return items;
}
private String loadJsonFromAsset() {
InputStream stream;
try {
stream = getBaseContext().getAssets().open("json_list.txt");
if (stream != null) {
int size = stream.available();
byte[] buffer = new byte[size];
stream.read(buffer);
stream.close();
if (buffer != null) {
return new String(buffer);
}
}
} catch (IOException e1) {
log("err--" + e1.toString());
}
return "";
}
And json file at assets
["item line 1","item line 2","item line 3"]

Related

How to change from Get Json Raw File to Get Json Url?

I have a code that works fine: Get Json from raw file (raw/video_list.json)
public class VideoListFragment extends BaseListFragment {
VideoAdapter adapter;
#Override
protected RecyclerView.Adapter getAdapter() {
if (adapter == null) {
String jsonStr = readRawFile();
Gson gson = new Gson();
VideoPage videoPage = gson.fromJson(jsonStr, VideoPage.class);
adapter = new VideoAdapter(videoPage);
}
return adapter;
}
String readRawFile() {
String content = "";
Resources resources = getContext().getResources();
InputStream is = null;
try {
is = resources.openRawResource(R.raw.video_list);
byte buffer[] = new byte[is.available()];
is.read(buffer);
content = new String(buffer);
} catch (IOException e) {
e.printStackTrace();
} finally {
if (is != null) {
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return content;
}
}
Now I want to get Json from Url,I copy Json in the video_list.json file to myjson.com and then get the url (https://api.myjson.com/bins/uyzbl), I change code:
public class VideoListFragment extends BaseListFragment {
VideoAdapter adapter;
#Override
protected RecyclerView.Adapter getAdapter() {
if (adapter == null) {
String jsonStr = readData("https://api.myjson.com/bins/71535");
Gson gson = new Gson();
VideoPage videoPage = gson.fromJson(jsonStr, VideoPage.class);
adapter = new VideoAdapter(videoPage);
}
return adapter;
}
String readData(String url) {
HttpsURLConnection con = null;
try {
URL u = new URL(url);
con = (HttpsURLConnection) u.openConnection();
con.connect();
BufferedReader br = new BufferedReader(new InputStreamReader(con.getInputStream()));
StringBuilder sb = new StringBuilder();
String line;
while ((line = br.readLine()) != null) {
sb.append(line + "\n");
}
br.close();
return sb.toString();
} catch (MalformedURLException ex) {
ex.printStackTrace();
} catch (IOException ex) {
ex.printStackTrace();
} finally {
if (con != null) {
try {
con.disconnect();
} catch (Exception ex) {
ex.printStackTrace();
}
}
}
return null;
}
}
No errors occurred in Android Studio but App unfortunately, app has stopped. Can you help me find and fix it?

Convert AsyncTask to RxJava

Bit new to Rx, so am looking for some help on converting the following AsyncTask to Rx, hopefully so I can visualize Rx a bit more with code that I already know that does something. I've found a few other SO answers that were somewhat relevant, but alot of them werent network requests and many used different operators for different answers, so am a bit confused.
Heres the AsyncTask:
Here is my Java code for an WhatsTheWeather App(all code from the MainActivity is included):
public class MainActivity extends AppCompatActivity {
EditText cityName;
TextView resultTextview;
public void findTheWeather(View view){
Log.i("cityName", cityName.getText().toString());
InputMethodManager mgr = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
mgr.hideSoftInputFromWindow(cityName.getWindowToken(), 0);
try {
String encodedCityName = URLEncoder.encode(cityName.getText().toString(), "UTF-8");
DownLoadTask task = new DownLoadTask();
task.execute("http://api.openweathermap.org/data/2.5/weather?q=" + cityName.getText().toString() + "&appid=a018fc93d922df2c6ae89882e744e32b");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
Toast.makeText(getApplicationContext(),"Could not find weather",Toast.LENGTH_LONG).show();
}
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
cityName = (EditText)findViewById(R.id.cityName);
resultTextview = (TextView) findViewById(R.id.resultTextView);
}
public class DownLoadTask extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... urls) {
String result = "";
URL url;
HttpURLConnection urlConnection = null;
try {
url = new URL(urls[0]);
urlConnection = (HttpURLConnection)url.openConnection();
InputStream inputStream = urlConnection.getInputStream();
InputStreamReader reader = new InputStreamReader(inputStream);
int data = reader.read();
while(data != -1){
char current = (char) data;
result +=current;
data = reader.read();
}
return result;
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
try {
String message = "";
JSONObject jsonObject = new JSONObject(result);
String weatherInfo = jsonObject.getString("weather");
Log.i("Weather content", weatherInfo);
JSONArray arr = new JSONArray(weatherInfo);
for(int i=0; i<arr.length(); i++){
JSONObject jsonPart = arr.getJSONObject(i);
String main = "";
String description="";
main = jsonPart.getString("main");
description = jsonPart.getString("description");
if(main != "" && description != ""){
message += main + ": "+ description + "\r\n"; //for a line break
}
}
if (message != ""){
resultTextview.setText(message);
} else {
Toast.makeText(getApplicationContext(),"Could not find weather",Toast.LENGTH_LONG).show();
}
} catch (JSONException e) {
Toast.makeText(getApplicationContext(),"Could not find weather",Toast.LENGTH_LONG).show();
}
}
}
Try this.
public void networkCall(final String urls) {
Observable.fromCallable(new Func0<String>() {
#Override
public String call() {
String result = "";
URL url = null;
HttpURLConnection urlConnection = null;
try {
url = new URL(urls);
urlConnection = (HttpURLConnection) url.openConnection();
InputStream inputStream = urlConnection.getInputStream();
InputStreamReader reader = new InputStreamReader(inputStream);
int data = reader.read();
while (data != -1) {
char current = (char) data;
result += current;
data = reader.read();
}
try {
String message = "";
JSONObject jsonObject = new JSONObject(result);
String weatherInfo = jsonObject.getString("weather");
Log.i("Weather content", weatherInfo);
JSONArray arr = new JSONArray(weatherInfo);
for (int i = 0; i < arr.length(); i++) {
JSONObject jsonPart = arr.getJSONObject(i);
String main = "";
String description = "";
main = jsonPart.getString("main");
description = jsonPart.getString("description");
if (main != "" && description != "") {
message += main + ": " + description + "\r\n"; //for a line break
}
}
return message;
} catch (JSONException e) {
Toast.makeText(getApplicationContext(), "Could not find weather", Toast.LENGTH_LONG).show();
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
})
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(new Subscriber<String>() {
#Override
public void onCompleted() {
}
#Override
public void onError(Throwable e) {
}
#Override
public void onNext(String message) {
if (message != ""){
resultTextview.setText(message);
} else {
Toast.makeText(getApplicationContext(),"Could not find weather",Toast.LENGTH_LONG).show();
}
}
});
}
But, i would recommend to use Retrofit and RxJava together.
There are couple of things you should know before integrating Retrofit.
Try not to use the older version of Retrofit
Retrofit2 is the one which you are supposed to use at current
Try avoiding code integration of Retrofit with RxJava or RxAndroid
at current(Too much complexity for beginner)
Make sure you are familiar with GSON or Jackson too.
HttpClient is depreciated while OkHttp is comparatively faster than HttpUrlConnection which is generally used by Retrofit2
Finally, here the link for the Retrofit2. It is well detailed and easy to understand. Jack Wharton has tried his best to make it simple to understand as possible.

How Can add a JSON Data to Array in JAVA

I have an project and I'm trying to convey to data from JSON Array to normal array. But I could not this. Can you help me if you know which and where code I add to in my project. My Main Activity file is here
public class MainActivity extends AppCompatActivity {
private TextView tvData;
private String[] stringArray;
protected ActionBarDrawerToggle mDrawerToggle;
private DrawerLayout mDrawerLayout;
private NavigationView mNavigationView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tvData = (TextView)findViewById(R.id.bilgi);
setupToolbar();
initNavigationDrawer();
new JSONTask().execute("http://192.168.1.36:8080/urunler/kategori_goster.php");
}
public class JSONTask extends AsyncTask<String,String,String>
{
#Override
protected String doInBackground(String... params) {
HttpURLConnection connection = null;
BufferedReader reader = null;
try {
URL url = new URL(params[0]);
connection = (HttpURLConnection) url.openConnection();
connection.connect();
InputStream stream = connection.getInputStream();
reader = new BufferedReader(new InputStreamReader(stream));
StringBuffer buffer = new StringBuffer();
String line="";
while((line = reader.readLine()) != null){
buffer.append(line);
}
String finalJson = buffer.toString();
JSONObject parentObject = new JSONObject(finalJson);
JSONArray parrentArray = parentObject.getJSONArray("uyelerimiz");
StringBuffer finalBufferedData = new StringBuffer();
for(int i=0;i<parrentArray.length(); i++)
{
JSONObject finalObject = parrentArray.getJSONObject(i);
String year = finalObject.getString("kategori_adi");
finalBufferedData.append(year + " \n");
}
return finalBufferedData.toString();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
} finally {
if(connection !=null)
{
connection.disconnect();
}
try {
if(reader !=null)
{
reader.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
return null;
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
tvData.setText(result);
}
}
JSON is working whitout any problem. I want to add my JSON data to my " private String[] stringArray;"
Here is how the JSON is formatted:
{
"uyelerimiz":[
{
"kategori_adi":"Bilgisayar"
},
{
"kategori_adi" ‌​:"Cep Telefonu"
},
{
"kategori_adi":"Saglik"
},
{
"kategori_adi":"Kirtas‌​iye"
}
]
}
private String[] parseJson(String response){
try {
JSONObject lJsonObject = new JSONObject(response);
JSONArray lJsonArray = lJsonObject.getJSONArray("uyelerimiz");
String[] lResult = new String[lJsonArray.length()];
for (int index = 0;index<lJsonArray.length();index++){
lResult[index] = lJsonArray.getJSONObject(index).getString("kategori_adi");
}
return lResult;
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}

How to insert one more item in a json existing structure with gson?

The code below generates correctly the first structure of the json file.
gson = new GsonBuilder().setPrettyPrinting().create();
AudDetHeader AudDetHeader = new AudDetHeader();
//ArrayList<OrderDetail> AudDetList = new ArrayList<OrderDetail>();
Map<String, AudDet> AudDetList = new HashMap<String, AudDet>();
AudDet AudDet = new AudDet();
AudDet.setLineId("1");
AudDet.setItemNumber("ABC");
AudDet.setQuantity(9);
AudDet.setPrice(10.00);
List<String> phones = new ArrayList<String>();
phones.add("24530001");
phones.add("24530002");
phones.add("24530003");
AudDet.setPhones(phones);
AudDetList.put("teste 2", AudDet);
AudDetHeader.setAudDetList(AudDetList);
Gson gson = new GsonBuilder().setPrettyPrinting().create();
String jsonString = gson.toJson(AudDetHeader);
BufferedWriter bufferedWriter = null;
try {
File file = new File(Environment.getExternalStorageDirectory() + "/download/test/test.json");
if(!file.exists()){
file.createNewFile();
}
FileWriter fileWriter = new FileWriter(file);
bufferedWriter = new BufferedWriter(fileWriter);
bufferedWriter.write(jsonString);
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (bufferedWriter != null){
bufferedWriter.close();
}
} catch (IOException ex) {
ex.printStackTrace();
}
}
The result of the code:
{
"Results": {
"teste 2": {
"itemNumber": "ABC",
"lineId": "1",
"phones": [
"24530001",
"24530002",
"24530003"
],
"price": 10.0,
"quantity": 9
}
}
}
I want to add a new item. My desire is to stay as the structure below.
{
"Results":{
"teste 2":{
"itemNumber":"ABC",
"lineId":"1",
"phones":[
"24530001",
"24530002",
"24530003"
],
"price":10.0,
"quantity":9
},
"teste 3":{
"itemNumber":"DEF",
"lineId":"2",
"phones":[
"30303030",
"40404040",
"505050"
],
"price":11.0,
"quantity":12
}
}
}
The AudDetHeader.class
public class AuditoriaDetalheHeader {
#SerializedName("Results")
private Map<String, AuditoriaDetalhe> AuditoriaDetalheList;
...
}
The AudDet.class
public class AuditoriaDetalhe {
String lineId = null;
String itemNumber = null;
int quantity = 0;
Double price = null;
List<String> phones = new ArrayList<String>();
...
}
Worked for me with this code!!!
Main class
private static File fileJson = new File(Environment.getExternalStorageDirectory() + "/download/test/test.json");
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.teste_criajson);
createJsonStructure();
Button btnSave = (Button)findViewById(R.id.btSave);
btnSalvar.setOnClickListener( new View.OnClickListener() {
public void onClick(View v) {
try {
String strFileJson = getStringFromFile(fileJson.toString());
JSONObject jsonObj = new JSONObject(strFileJson);
Gson gson = new Gson();
JsonParser jsonParser = new JsonParser();
String idAud = "10";
AudDet ad = new AudDet();
ad.setLineId("2");
ad.setItemNumber("DEF");
ad.setQuantity(22);
ad.setPrice(22.22);
List<String> phones = new ArrayList<String>();
phones.add("22");
phones.add("22");
phones.add("22");
ad.setPhones(phones);
String jsonStr = jsonParser.parse(gson.toJson(ad)).toString();
JSONObject JSONObject = new JSONObject(jsonStr);
jsonObj.getJSONObject("Results").put(idAud, JSONObject);
writeJsonFile(fileJson, jsonObj.toString());
} catch (Exception e1) {
e1.printStackTrace();
}
}
});
If do not exists json file, then i create with basic structure for insert the itens.
public static void createJsonStructure(){
if(!fileJson.exists()){
try {
fileJson.createNewFile();
String jsonString = "{\"Results\":{}}";
writeJsonFile(fileJson, jsonString);
} catch (IOException e) {
e.printStackTrace();
}
}
}
Open the json file to get the string format, and prepare to insert a new item:
public static String getStringFromFile (String filePath) throws Exception {
File fl = new File(filePath);
FileInputStream fin = new FileInputStream(fl);
String ret = convertStreamToString(fin);
//Make sure you close all streams.
fin.close();
return ret;
}
public static String convertStreamToString(InputStream is) throws Exception {
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line).append("\n");
}
return sb.toString();
}
Writes into the json file that already exists:
public static void writeJsonFile(File file, String json)
{
BufferedWriter bufferedWriter = null;
try {
if(!file.exists()){
file.createNewFile();
}
FileWriter fileWriter = new FileWriter(file);
bufferedWriter = new BufferedWriter(fileWriter);
bufferedWriter.write(json);
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (bufferedWriter != null){
bufferedWriter.close();
}
} catch (IOException ex) {
ex.printStackTrace();
}
}
}

how to create a string representation of json

hey there guys and girls i have this code that saves json as a string representation, i still haveing a little trouble understanding how the entity section works, and need to know how to change my code so that it works, this is the error im getting,
Error saving string java.lang.NumberFormatException: unable to parse '[{"story_name":"Story One"},{"story_name":"Story Two"},{"story_name":"Story Three"},{"story_name":"Story Four"},{"story_name":"Story Five"},{"story_name":"Story Six"}]' as integer
i was getting help from someone last night that almost got me there but still need a little more understanding of how it works and wht i get the parse error here is my full code
public class MainActivity extends Activity {
String entityString = null;
String storyObj = "";
Object json = null;
HttpEntity entity = null;
InputStream is = null;
Integer responseInteger = null;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
//button that saves the file from mySQL
Button save = (Button) findViewById(R.id.downloadBtn);
save.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
saveJson();
}
});
//Button that opens the file from InternalMemory
Button open = (Button) findViewById(R.id.showBtn);
open.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
openJson();
}
});
//end of onCreate()
}
//saveJson pull a JSON file from mySQl server then saves that file in its JSON type eg .json
public void saveJson(){
TextView test = (TextView) findViewById(R.id.showView);
try{
//connects to mySQL
HttpClient client = new DefaultHttpClient();
HttpPost post = new HttpPost("http://10.0.2.2/textures_story_list.php");
HttpResponse response = client.execute(post);
//captures the response
entity = response.getEntity();
InputStream entityStream = entity.getContent();
StringBuilder entityStringBuilder = new StringBuilder();
byte [] buffer = new byte[1024];
int bytesReadCount;
while ((bytesReadCount = entityStream.read(buffer)) > 0) {
entityStringBuilder.append(new String(buffer, 0, bytesReadCount));
}
entityString = entityStringBuilder.toString();
responseInteger = Integer.valueOf(entityString);
}catch(Exception e) {
Log.e("log_tag", "Error in http connection "+e.toString());
}
try{
//is = entity.getContent();
String FILENAME = "story.json";
//gives file name
FileOutputStream output = openFileOutput(FILENAME, MODE_WORLD_READABLE);
//creates new StreamWriter
OutputStreamWriter writer = new OutputStreamWriter(output);
//writes json with file name story.json
writer.write(entityString);
writer.flush();
//closes writer
writer.close();
}catch(Exception e) {
Log.e("log_tag", "Error saving string "+e.toString());
}
//end of saveJson()
}
public void openJson(){
TextView test = (TextView) findViewById(R.id.showView);
try{
FileInputStream fileInput = openFileInput("story.json");
BufferedReader inputReader = new BufferedReader(new InputStreamReader(fileInput, "UTF-8"), 8);
StringBuilder strBuilder = new StringBuilder();
String line = null;
while ((line = inputReader.readLine()) != null) {
strBuilder.append(line + "\n");
}
fileInput.close();
storyObj = strBuilder.toString();
}catch(IOException e){
Log.e("log_tag", "Error building string "+e.toString());
}
try{
JSONArray jArray = new JSONArray(storyObj);
String storyNames = "";
for(int i = 0;i<jArray.length();i++){
storyNames += jArray.getJSONObject(i).getString("story_name") +"\n";
}
test.setText(storyNames);
}catch(JSONException e) {
Log.e("log_tag", "Error returning string "+e.toString());
}
return;
//and of openJson()
}
//end of class body
}
My guess it your code failed at this lines:
responseInteger = Integer.valueOf(entityString);
After a little inspection, I see that your JSON is:
[{"story_name":"Story One"},{"story_name":"Story Two"},{"story_name":"Story Three"},{"story_name":"Story Four"},{"story_name":"Story Five"},{"story_name":"Story Six"}]
A closer inspection using JSON Viewer, I see that your structure is like this:
The problem is
I don't see any integer in this JSON. You might have to use a combination of JSONObject and JSONArray to parse your it properly.
Your problem is this line
responseInteger = Integer.valueOf(entityString);
entityString is
'[{"story_name":"Story One"},{"story_name":"Story Two"},{"story_name":"Story Three"},{"story_name":"Story Four"},{"story_name":"Story Five"},{"story_name":"Story Six"}]'
And when Integer.valueOf tries to parse it, it can't parse it as an integer, so it throws a NumberFormatException.
Sample JSon string:
{
Stories:
[
{
"story_name": "Story One"
},
{
"story_name": "Story Two"
}
]
}
Create a Class:
public class Story
{
public String stort_name;
}
class CollectionOfStories
{
public List<Story> Stories;
public CollectionOfSections()
{
Stories= new ArrayList<Story>();
}
}
Finally:
private CollectionOfStories convertDataFromJSonToObject(String jsonString)
{
JSONObject jso;
CollectionOfStories colStories = new CollectionOfStories();
try
{
jso = new JSONObject(jsonString);
JSONArray ja = jso.getJSONArray("Stories");
for (int i = 0; i < ja.length(); i++)
{
Story s = new Story();
JSONObject jsonSection = ja.getJSONObject(i);
s.stort_name = jsonSection.getString("story_name");
//add it to sections list
colStories.Stories.add(s);
}
}
catch (NumberFormatException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
catch (JSONException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
return colStories;
}

Categories

Resources