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;
}
Related
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.
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"]
This question already has an answer here:
convert json to excel in java
(1 answer)
Closed 8 months ago.
I am new to Android Dev,This is my first Question in SO. i try to export my reports in Excel format. so i try to create the Excel file.Here is the code.
I am struck with get the json and put into the ROW and CELL
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
TextView hwtxt = (TextView)findViewById(R.id.hw);
HSSFWorkbook workbook = new HSSFWorkbook();
HSSFSheet firstSheet = workbook.createSheet("Sheet1");
String url = "http://192.168.1.13:8090/Sanjay_API/showBalanceAmtList.php";
List<NameValuePair> params = new ArrayList<>();
params.add(new BasicNameValuePair("hwtxt", hwtxt.getText().toString()));
try {
JSONObject parentObject = new JSONObject(getJSONUrl(url, params));
JSONArray data = parentObject.getJSONArray("balance_list");
MyArrList = new ArrayList<HashMap<String, String>>();
HashMap<String, String> map;
for(int i = 0; i < data.length(); i++){
JSONObject c = data.getJSONObject(i);
String myVal1 = c.getString("entry_date");
System.out.println(myVal1);
}
}catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
FileOutputStream fos = null;
try {
String str_path = Environment.getExternalStorageDirectory().toString();
File file;
//String CurrentDateAndTime = java.text.DateFormat.getDateTimeInstance().format(new Date());
file = new File(str_path, getString(R.string.app_name) + ".xls");
fos = new FileOutputStream(file);
workbook.write(fos);
} catch (IOException e) {
e.printStackTrace();
} finally {
if (fos != null) {
try {
fos.flush();
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
Toast.makeText(MainActivity.this, "Excel Sheet Generated", Toast.LENGTH_SHORT).show();
}
}
public String getJSONUrl(String url,List<NameValuePair> params) {
StringBuilder str = new StringBuilder();
HttpClient client = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
try {
httpPost.setEntity(new UrlEncodedFormEntity(params));
HttpResponse response = client.execute(httpPost);
StatusLine statusLine = response.getStatusLine();
int statusCode = statusLine.getStatusCode();
if (statusCode == 200) { // Download OK
HttpEntity entity = response.getEntity();
InputStream content = entity.getContent();
BufferedReader reader = new BufferedReader(new InputStreamReader(content));
String line;
while ((line = reader.readLine()) != null) {
str.append(line);
}
} else {
Log.e("Log", "Failed to download result..");
}
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return str.toString();
}
And, I have a data in json which is return from APT using PHP, My json is
{
"vnumber": [{
"vid": "1",
"vnumber": "STAT01",
"vname": "STAT01",
"vyear": "2011",
"fcdate": "22/12/2017",
"insdate": "22/12/2017",
"perdate": "22/12/2017",
"gtax": "0123456",
"polcer": "TEST DEMO CERTIFY"
}, {
"vid": "2",
"vnumber": "STAT02",
"vname": "STAT02",
"vyear": "2015",
"fcdate": "12/12/2012",
"insdate": "12/12/2012",
"perdate": "12/12/2012",
"gtax": "100",
"polcer": "100"
}]
}
I dont know how to export my data in excel format in SD Card.
Can you please try following.
File csvFile = new File(directory, Utils.CSV_FILE_NAME);
try {
csvFile.createNewFile();
CSVWriter csvWrite = new CSVWriter(new FileWriter(csvFile));
String heading[] = {"vid", "vnumber", "vname", "vyear", "fcdate", "insdate", "perdate", "gtax", "polcer"};
csvWrite.writeNext(heading);
for (int i = 0; i < arrayList.size(); i++) {
YourModel model = arrayList.get(i); // You can also use JsonObject from Json array.
String arrStr[] = {String.valueOf(model.getVid()), String.valueOf(model.getVnumber()), model.getVname(), model.getVyear(), model.getFcdate(), model.getInsdate(), model.getPerdate(),model.getGtax(), model.getPolcer() };
csvWrite.writeNext(arrStr);
}
csvWrite.close();
} catch (Exception sqlEx) {
Log.e(TAG, sqlEx.getMessage(), sqlEx);
}
Android is basically Java. Here is one question on Stackoverflow itself that can help you with this
convert json to excel in java
I have spent too much time for this implementation and finally below code is working for me
Add the following dependency in build.gradle
implementation 'org.apache.poi:poi:3.17'
Use the following code for Convert Java Object into Excel Cells and Row and finally create an excel file and download it to your phone storage.
HSSFWorkbook hssfWorkbook = new HSSFWorkbook();
HSSFSheet hssfSheet = hssfWorkbook.createSheet("Custom Sheet");
//---------------
HSSFRow hssfRowMainTitle = hssfSheet.createRow(0);
hssfRowMainTitle.createCell(0).setCellValue("Document");
//-------------
HSSFRow hssfRowTitle = hssfSheet.createRow(1);
hssfRowTitle.createCell(0).setCellValue("srno");
hssfRowTitle.createCell(1).setCellValue("date");
hssfRowTitle.createCell(2).setCellValue("type");
hssfRowTitle.createCell(3).setCellValue("transactionid");
//--------------
int row = 2;
int srNo = 1;
for (Ledger a : currentFilterDataList) {
HSSFRow hssfRow = hssfSheet.createRow(row);
hssfRow.createCell(0).setCellValue(srNo);
hssfRow.createCell(1).setCellValue(a.getDate());
hssfRow.createCell(2).setCellValue(a.getType());
hssfRow.createCell(3).setCellValue(a.getVoucherNo());
row++;
srNo++;
}
//---------
File path = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS + File.separator);
File file = new File(path.toString());
file.mkdirs();
String fileName = path + "/" + "transaction_" + System.currentTimeMillis() + ".xls";
try {
FileOutputStream fileOutputStream = new FileOutputStream(fileName);
hssfWorkbook.write(fileOutputStream);
fileOutputStream.flush();
fileOutputStream.close();
showSnackBar(getContext(), mBinding.getRoot(), "File downloaded successfully \n " + path);
} catch (IOException e) {
e.printStackTrace();
}
URL JSON Parsing Error. Please check my code.
{
"info": "Central Bank of Myanmar",
"description": "Official Website of Central Bank of Myanmar",
"timestamp": "1448611200",
"rates":
{
"USD": "1,300.0",
"CZK": "51.055",
"JPY": "1,060.2",
}
}
Activity code is:
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.json_object);
TextView output = (TextView) findViewById(R.id.textView1);
String data = "";
try {
String ka =callURL("http://forex.cbm.gov.mm/api/latest");
JSONObject object = new JSONObject(ka);
JSONObject servicedata = object.getJSONObject("rates");
String USD = servicedata.getString("USD");
data += "USD Currency " + USD +" ";
output.setText(data);
} catch (JSONException e) {
e.printStackTrace();
}
}
Call URL give me error.
public static String callURL(String myURL) {
System.out.println("Requeted URL:" + myURL);
StringBuilder sb = new StringBuilder();
URLConnection urlConn = null;
InputStreamReader in = null;
try {
URL url = new URL(myURL);
urlConn = url.openConnection();
if (urlConn != null)
urlConn.setReadTimeout(60 * 1000);
if (urlConn != null && urlConn.getInputStream() != null) {
in = new InputStreamReader(urlConn.getInputStream(),
Charset.defaultCharset());
BufferedReader bufferedReader = new BufferedReader(in);
if (bufferedReader != null) {
int cp;
while ((cp = bufferedReader.read()) != -1) {
sb.append((char) cp);
}
bufferedReader.close();
}
}
in.close();
} catch (Exception e) {
throw new RuntimeException("Exception while calling URL:"+ myURL, e);
}
return sb.toString();
}
Try with android volly library It is developed by Google.
You can easily convert json to java and vice versa.
if (android.os.Build.VERSION.SDK_INT > 9) {
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
}
I put this code under the setContentView and code it work. Thank your advertises.
I spent the time about one day for this.
i am working on an app in which i have to populate gridview of images dynamically. I am getting an array of image ids from server, i am decoding json array and getting the image ids. now i have stored all the images in my drawable folder, i want to show the images of the ids i am getting from the json, but i am stuck at this point i don't know how this. help
this is my main activity
public class MainActivity extends Activity {
GridView grid ;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
grid = (GridView)findViewById(R.id.grid_view);
grid.setAdapter(new Adapter(this));
Button play = (Button)findViewById(R.id.play);
play.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
try {
playgame();
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
protected void playgame() throws JSONException {
if(cardcount >=1 ){
BufferedReader reader=null;
data_to_send = "userId=" + userId ;
try
{
Log.e("inside try block", "get text");
// Defined URL where to send data
URL url = new URL("http://172.16.10.5/Ankur/andapp/request_Play.php");
// Send POST data request
URLConnection conn = url.openConnection();
conn.setDoOutput(true);
OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());
wr.write(data_to_send);
wr.flush();
// Get the server response
reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
StringBuilder sb = new StringBuilder();
String line = null;
// Read Server Response
while((line = reader.readLine()) != null)
{
// Append server response in string
sb.append(line + "\n");
Log.e("inside", "while loop");
}
play_response = sb.toString();
}
catch(Exception ex)
{
}
finally
{
try
{
reader.close();
}
catch(Exception ex) {}
}
Log.e("play response from the server", ""+play_response);
}else
{
Toast.makeText(getApplicationContext(), "Sorry you don't have cards.buy a new card now", Toast.LENGTH_LONG).show();
}
JSONObject jo = new JSONObject(play_response);
pos1 = jo.getString("0");
pos2 = jo.getString("1");
pos3 = jo.getString("2");
pos4= jo.getString("3");
pos5 = jo.getString("4");
pos6= jo.getString("5");
pos7= jo.getString("6");
pos8= jo.getString("7");
pos9= jo.getString("8");
Log.e("value of 1st place of array", "array value "+pics[7]);
}
i recommend to use Loader. see this [documentation] (http://developer.android.com/guide/components/loaders.html)
thus you can transfer images loading in not ui thread in Loade