Return a new thymeleaf page fragment and some file from spring controller - spring

Tell me how to properly implement the spring controller. I want it to return a new thymeleafe page fragment and Excel file at the same time.
I know how to implement a controller to return a page fragment:
#GetMapping("/some_url")
public String updateFragment(Model model) {
model.addAttribute("attribute", someAtribute);
return "some_page :: fragment";
}
And I know how to implement a controller for downloading files:
#GetMapping("some_url")
public void getReport(HttpServletResponse response) throws IOException {
response.setContentType("application/octet-stream");
String headerKey = "Content-Disposition";
String headerValue = "attachment; filename=file.xlsx";
response.setHeader(headerKey, headerValue);
try {
FileInputStream inputStream = new FileInputStream(new File("path_to_file"));
Workbook workbook = WorkbookFactory.create(inputStream);
Sheet sheet = workbook.getSheetAt(0);
int row = 12;
Row exampleRow = sheet.getRow(12);
int count = 1;
for (SIZForKomplex s : objectList) {
if (s.getNumber() != 0) {
sheet.getRow(row).setRowStyle(exampleRow.getRowStyle());
sheet.getRow(row).setHeight(exampleRow.getHeight());
for (int i = 0; i < 8; i++) {
sheet.getRow(row).getCell(i).setCellStyle(exampleRow.getCell(i).getCellStyle());
}
sheet.getRow(row).getCell(0).setCellValue(count);
sheet.getRow(row).getCell(1).setCellValue(s.getNomenclatureNumber());
sheet.getRow(row).getCell(2).setCellValue(s.getNamesiz());
sheet.getRow(row).getCell(3).setCellValue(s.getSize());
sheet.getRow(row).getCell(4).setCellValue(s.getHeight());
sheet.getRow(row).getCell(5).setCellValue(s.getNumber());
sheet.getRow(row).getCell(6).setCellValue(sizRepository.findById(s.getId()).orElseThrow().getEd_izm());
sheet.getRow(row).getCell(7).setCellValue(" ");
row++;
count++;
}
}
inputStream.close();
ServletOutputStream outputStream = response.getOutputStream();
workbook.write(outputStream);
workbook.close();
outputStream.close();
} catch (IOException | EncryptedDocumentException
ex) {
ex.printStackTrace();
}
}
But how do I combine this. I need to update the data on the page and download the Excel file

Related

Spring Boot - Handle CSV as well as Excel Multipart file

I have a REST API in Spring Boot Application that takes in a param of type Multipart file.
There is possibility that user may import either CSV file or Excel(.xlsx / .xsl) file of huge size which needs to be handled.
I am using Apache POI to read Excel type file and it is working fine. To my existing code, how do I efficiently handle CSV file reading also
Below is Excel file Reading Code:
#RequestMapping(value="/read", method = RequestMethod.POST)
#Transactional
public Map<String, String> read(#RequestParam("file") MultipartFile file) {
Map<String, String> response = new ArrayList();
if (!file.isEmpty()) {
ByteArrayInputStream stream;
Workbook wb;
StringBuilder contentSb = new StringBuilder();
try {
stream = new ByteArrayInputStream(file.getBytes());
wb = WorkbookFactory.create(stream);
org.apache.poi.ss.usermodel.Sheet sheet = wb.getSheetAt(wb.getActiveSheetIndex());
Iterator<Row> rowIterator = sheet.rowIterator();
System.out.println("Processing Excel file");
for (int rowIndex = 0; rowIndex <= sheet.getLastRowNum(); rowIndex++) {
Row row = sheet.getRow(rowIndex);
if (row != null) {
Cell cell = row.getCell(0);
if (cell != null) {
contentSb.append(cell.getStringCellValue()+",");
}
}
}
System.out.println("Processed Excel file");
return response;
} catch (Exception e) {
e.printStackTrace();
}
}
else {
return response;
}
}
Thank you in advance!

loopj JsonObject with inside JsonArray JsonObjects

I have a Webservice which give me back this:
{"result":[{"Id":"20","temperatura":"34","humedad":"29","Insertado":"2016-07-01 12:19:42"},{"Id":"21","temperatura":"34","humedad":"29","Insertado":"2016-07-01 12:34:42"},{"Id":"22","temperatura":"35","humedad":"28","Insertado":"2016-07-01 12:49:43"},{"Id":"23","temperatura":"35","humedad":"19","Insertado":"2016-07-01 13:29:06"},{"Id":"24","temperatura":"31","humedad":"18","Insertado":"2016-07-01 13:44:07"},{"Id":"25","temperatura":"33","humedad":"16","Insertado":"2016-07-01 13:59:10"}]}
This is an Object, which has and Array, and the array has many objects.
Here is my code. I am using loopj library-
private void CaptarParametros(String idObjeto) {
AsyncHttpClient client = new AsyncHttpClient();
RequestParams params = new RequestParams();
params.put(UtilitiesGlobal.SENSOR_ID, idObjeto);
RequestHandle post = client.post(this, SENSORS_URL, params, new JsonHttpResponseHandler() {
#Override
public void onStart() {
// called before request is started
}
#TargetApi(Build.VERSION_CODES.KITKAT)
#Override
public void onSuccess(int statusCode, Header[] headers, JSONObject response) {
// called when response HTTP status is "200 OK"
JSONObject jsonobject = null;
JSONObject dht11JSONbject = null;
JSONArray dht11JSONarray = null;
try {
jsonobject = new JSONObject(String.valueOf(response));
dht11JSONbject = jsonobject.getJSONObject("result");
dht11JSONarray = new JSONArray(dht11JSONbject);
JSONArray dht11 = dht11JSONarray.getJSONArray(0);
for (int i = 0; i < dht11JSONarray.length(); i++) {
JSONObject item = dht11.getJSONObject(i);
String temperatura = item.getString("temperatura");
String humedad = item.getString("temperatura");
//Log.i(UtilitiesGlobal.TAG, "onSuccess: loopj " + usuarioiJSONbject);
Log.i(UtilitiesGlobal.TAG, "onSuccess: loopj " + temperatura + humedad);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
But I get error like this:
org.json.JSONException: Value [{"Id":"19","temperatura":"35","humedad":"16","Insertado":"2016-07-01 12:19:24"}] at result of type org.json.JSONArray cannot be converted to JSONObject
I would appreciate any help.- I need to extract "temperature" and humedad" in separate arrays since later I have to use it in MPAndroidChat to make tow linechart, one chart for one set of parameters and another one for other parameters.
Solution is here:
try {
jsonobject = new JSONObject(String.valueOf(response));
//dht11JSONbject = jsonobject.getJSONObject("result");
List<String> allNames = new ArrayList<String>();
JSONArray cast = jsonobject.getJSONArray("result");
for (int i=0; i<cast.length(); i++) {
JSONObject parametrosdht11 = cast.getJSONObject(i);
String temperatura = parametrosdht11.getString("temperatura");
String humedad = parametrosdht11.getString("humedad");
allNames.add(temperatura);
allNames.add(humedad);
//Log.i(UtilitiesGlobal.TAG, "onSuccess: loopj " + usuarioiJSONbject);
Log.i(UtilitiesGlobal.TAG, "onSuccess: loopj " +"temperatura: "+ temperatura +" humedad: " +humedad);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
We have a String with many sub_objects, then we have to put them into an array or List.
Take the solution from:
how to parse JSONArray in android

Transferring assets : Error code 4005 ASSET_UNAVAILABLE

This is driving me crazy. I wrote a code quite a while ago that was working, and opened it again and it happens that I am not able to transfer my assets from the mobile to the wearable device.
public Bitmap loadBitmapFromAsset(Asset asset) {
if (asset == null) {
throw new IllegalArgumentException("Asset must be non-null");
}
// convert asset into a file descriptor and block until it's ready
Log.d(TAG, "api client" + mApiClient);
DataApi.GetFdForAssetResult result = Wearable.DataApi.getFdForAsset(mApiClient, asset).await();
if (result == null) {
Log.w(TAG, "getFdForAsset returned null");
return null;
}
if (result.getStatus().isSuccess()) {
Log.d(TAG, "success");
} else {
Log.d(TAG, result.getStatus().getStatusCode() + ":" + result.getStatus().getStatusMessage());
}
InputStream assetInputStream = result.getInputStream();
if (assetInputStream == null) {
Log.w(TAG, "Requested an unknown Asset.");
return null;
}
// decode the stream into a bitmap
return BitmapFactory.decodeStream(assetInputStream);
}
And this is the code from which I call the loadBitmapFrom Asset method.
DataMap dataMap = DataMapItem.fromDataItem(event.getDataItem()).getDataMap();
ArrayList<DataMap> dataMaps = dataMap.getDataMapArrayList("dataMaps");
ArrayList<String> names = new ArrayList<>();
ArrayList<String> permalinks = new ArrayList<>();
ArrayList<Asset> images = new ArrayList<>();
for (int i = 0 ; i < dataMaps.size() ; i++) {
Log.d(TAG, dataMaps.get(i).getString("name"));
names.add(dataMaps.get(i).getString("name"));
permalinks.add(dataMaps.get(i).getString("permalink"));
images.add(dataMaps.get(i).getAsset("image"));
}
editor.putInt("my_selection_size", names.size());
for (int i=0; i <names.size() ; i++) {
editor.putString("my_selection_name_" + i, names.get(i));
editor.putString("my_selection_permalink_" + i, permalinks.get(i));
Log.d(TAG, "asset number " + i + " " + images.get(i));
Bitmap bitmap = loadBitmapFromAsset(images.get(i));
ByteArrayOutputStream stream = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.PNG, 100, stream);
byte[] byteArray = stream.toByteArray();
String encoded = Base64.encodeToString(byteArray, Base64.DEFAULT);
editor.putString("my_selection_image_" + i, encoded);
}
And on the mobile side :
private void sendData(PutDataMapRequest dataMap) {
PutDataRequest request = dataMap.asPutDataRequest();
request.setUrgent();
com.google.android.gms.common.api.PendingResult<DataApi.DataItemResult> pendingResult = Wearable.DataApi.putDataItem(mApiClient, request);
pendingResult.setResultCallback(new ResultCallback<DataApi.DataItemResult>() {
#Override
public void onResult(DataApi.DataItemResult dataItemResult) {
com.orange.radio.horizon.tools.Log.d(TAG, "api client : " + mApiClient);
if (dataItemResult.getStatus().isSuccess()) {
com.orange.radio.horizon.tools.Log.d(TAG, "message successfully sent");
} else if (dataItemResult.getStatus().isInterrupted()) {
com.orange.radio.horizon.tools.Log.e(TAG, "couldn't send data to watch (interrupted)");
} else if (dataItemResult.getStatus().isCanceled()) {
com.orange.radio.horizon.tools.Log.e(TAG, "couldn't send data to watch (canceled)");
}
}
});
Log.d(TAG, "Sending data to android wear");
}
class ConfigTask extends AsyncTask<String, Void, String> {
ArrayList<WatchData> mitems;
int mType;
public ConfigTask(ArrayList<WatchData> items, int type)
{
mitems = items;
mType = type;
}
protected String doInBackground(String... str)
{
DataMap dataMap;
ArrayList<DataMap> dataMaps = new ArrayList<>();
Bitmap bitmap = null;
for (int i = 0 ; i < mitems.size() ; i++) {
dataMap = new DataMap();
URL url = null;
try {
url = new URL(mitems.get(i).mUrlSmallLogo);
Log.d(TAG, "url : " + url);
} catch (MalformedURLException e) {
e.printStackTrace();
}
try {
bitmap = BitmapFactory.decodeStream(url.openConnection().getInputStream());
} catch (IOException e) {
e.printStackTrace();
}
Asset asset = createAssetFromBitmap(bitmap);
dataMap.putAsset("image", asset);
dataMap.putString("name", mitems.get(i).mName);
dataMap.putString("permalink", mitems.get(i).mPermalink);
dataMaps.add(dataMap);
}
PutDataMapRequest request = null;
switch (mType) {
case 0 :
request = PutDataMapRequest.create(SELECTION_PATH);
break;
case 1 :
request = PutDataMapRequest.create(RADIOS_PATH);
break;
case 2 :
request = PutDataMapRequest.create(PODCASTS_PATH);
break;
}
request.getDataMap().putDataMapArrayList("dataMaps", dataMaps);
request.getDataMap().putString("", "" + System.currentTimeMillis()); //random data to refresh
Log.d(TAG, "last bitmap : " + bitmap);
Log.d(TAG, "===============================SENDING THE DATAMAP ARRAYLIST==================================");
sendData(request);
return "h";
}
protected void onPostExecute(String name)
{
}
}
When executing that code, I see the following error happening :
02-02 14:47:59.586 7585-7601/? D/WearMessageListenerService﹕ 4005:ASSET_UNAVAILABLE
I saw that related thread Why does Wearable.DataApi.getFdForAsset produce a result with status 4005 (Asset Unavailable)? but it didn't really help me
I recently had the same problem... I solved it by updating the Google play service, and adding the same signing configuration to both the app and the wearable module. If it doesn't work on the first build go to "invalidate caches / restart" in files and it should work.

Convert csv to xls/xlsx using Apache poi?

I need to convert csv to xls/xlsx in my project? How can i do that? Can anyone post me some examples? I want to do it with Apache poi. I also need to create a cell from java side.
You can try following method to create xlsx file using apache-poi.
public static void csvToXLSX() {
try {
String csvFileAddress = "test.csv"; //csv file address
String xlsxFileAddress = "test.xlsx"; //xlsx file address
XSSFWorkbook workBook = new XSSFWorkbook();
XSSFSheet sheet = workBook.createSheet("sheet1");
String currentLine=null;
int RowNum=0;
BufferedReader br = new BufferedReader(new FileReader(csvFileAddress));
while ((currentLine = br.readLine()) != null) {
String str[] = currentLine.split(",");
RowNum++;
XSSFRow currentRow=sheet.createRow(RowNum);
for(int i=0;i<str.length;i++){
currentRow.createCell(i).setCellValue(str[i]);
}
}
FileOutputStream fileOutputStream = new FileOutputStream(xlsxFileAddress);
workBook.write(fileOutputStream);
fileOutputStream.close();
System.out.println("Done");
} catch (Exception ex) {
System.out.println(ex.getMessage()+"Exception in try");
}
}
We can use SXSSF Jar in which we can parse a long file as below:
public static void main( String[] args ) {
try {
// String fName = args[ 0 ];
String csvFileAddress = "C:\\Users\\psingh\\Desktop\\test\\New folder\\GenericDealerReport - version6.txt"; //csv file address
String xlsxFileAddress = "C:\\Users\\psingh\\Desktop\\trial\\test3.xlsx"; //xlsx file address
SXSSFWorkbook workBook = new SXSSFWorkbook( 1000 );
org.apache.poi.ss.usermodel.Sheet sheet = workBook.createSheet( "sheet1" );
String currentLine = null;
int RowNum = -1;
BufferedReader br = new BufferedReader( new FileReader( csvFileAddress ) );
while ( ( currentLine = br.readLine() ) != null ) {
String str[] = currentLine.split( "\\|" );
RowNum++;
Row currentRow = sheet.createRow( RowNum );
for ( int i = 0; i < str.length; i++ ) {
currentRow.createCell( i )
.setCellValue( str[ i ] );
}
}
DateFormat df = new SimpleDateFormat( "yyyy-mm-dd-HHmmss" );
Date today = Calendar.getInstance()
.getTime();
String reportDate = df.format( today );
FileOutputStream fileOutputStream = new FileOutputStream( xlsxFileAddress );
workBook.write( fileOutputStream );
fileOutputStream.close();
//System.out.println( "Done" );
}
catch ( Exception ex ) {
System.out.println( ex.getMessage() + "Exception in try" );
}
}
public static void convertCsvToXlsx(String xlsLocation, String csvLocation) throws Exception {
SXSSFWorkbook workbook = new SXSSFWorkbook();
SXSSFSheet sheet = workbook.createSheet("Sheet");
AtomicReference<Integer> row = new AtomicReference<>(0);
Files.readAllLines(Paths.get(csvLocation)).forEach(line -> {
Row currentRow = sheet.createRow(row.getAndSet(row.get() + 1));
String[] nextLine = line.split(",");
Stream.iterate(0, i -> i + 1).limit(nextLine.length).forEach(i -> {
currentRow.createCell(i).setCellValue(nextLine[i]);
});
});
FileOutputStream fos = new FileOutputStream(new File(xlsLocation));
workbook.write(fos);
fos.flush();
}
I have found SXSSFWorkbook really faster then XSSFWorkbook. Here is the modified code:
try {
String csvFileInput = "inputFile.csv";
String xlsxFileOutput ="outputFile.xls";
LOGGER.error(csvFileInput);
LOGGER.error( xlsxFileOutput);
SXSSFWorkbook workBook = new SXSSFWorkbook();
Sheet sheet = workBook.createSheet(transformBean.getOutputFileName());
String currentLine = null;
int RowNum = 0;
BufferedReader br = new BufferedReader(new FileReader(csvFileInput));
while ((currentLine = br.readLine()) != null) {
String str[] = currentLine.split(",");
RowNum++;
Row currentRow = sheet.createRow(RowNum);
for (int i = 0; i < str.length; i++) {
currentRow.createCell(i).setCellValue(str[i]);
}
}
FileOutputStream fileOutputStream = new FileOutputStream(xlsxFileOutput);
workBook.write(fileOutputStream);
fileOutputStream.close();
System.out.println("Done");
} catch (Exception ex) {
System.out.println(ex.getMessage() + "Found Exception");
}
if(new File(newFileName).isFile()) return;
#SuppressWarnings("resource")
HSSFWorkbook wb = new HSSFWorkbook();
Row xlsRow;
Cell xlsCell;
HSSFSheet sheet = wb.createSheet("sheet1");
int rowIndex = 0;
for(CSVRecord record : CSVFormat.EXCEL.parse(new FileReader(fileName))) {
xlsRow = sheet.createRow(rowIndex);
for(int i = 0; i < record.size(); i ++){
xlsCell = xlsRow.createCell(i);
xlsCell.setCellValue(record.get(i));
}
rowIndex ++;
}
FileOutputStream out = new FileOutputStream(newFileName);
wb.write(out);
out.close();
Try this one if you have inputstream
public static XSSFWorkbook csvToXLSX(InputStream inputStream) throws IOException {
XSSFWorkbook workBook = new XSSFWorkbook();
try(BufferedReader br = new BufferedReader(new InputStreamReader(inputStream))) {
Sheet sheet = workBook.createSheet("sheet1");
String currentLine=null;
int rowNum=0;
while ((currentLine = br.readLine()) != null) {
String[] str = currentLine.split(",");
rowNum++;
Row currentRow=sheet.createRow(rowNum);
for(int i=0;i<str.length;i++){
currentRow.createCell(i).setCellValue(str[i]);
}
}
log.info("CSV file converted to the workbook");
return workBook;
} catch (Exception ex) {
log.error("Exception while converting csv to xls {}",ex);
}finally {
if (Objects.nonNull(workBook)) {
workBook.close();
}
}
return workBook;
}

Customize toast in asyntask in android

I just wanna ask if it is possible to use my customize toast in onPostExecute of my Asyntask in android. If yes then how? I tried to put it on the onPostExecute but I got a lot red lines. Here is my code for my customize toast:
Typeface tfR= Typeface.createFromAsset(getAssets(), "Gothic_Regular.TTF");
LayoutInflater inflater = getLayoutInflater();
View layouttoast = inflater.inflate(R.layout.toast_bg, (ViewGroup)findViewById(R.id.toastAttribute));
TextView msg = ((TextView) layouttoast.findViewById(R.id.txt_toast));
msg.setTypeface(tfR);
msg.setText(toast_msg);
msg.setTextSize(TypedValue.COMPLEX_UNIT_PX,16);
Toast mytoast = new Toast(getBaseContext());
mytoast.setView(layouttoast);
mytoast.setGravity(Gravity.CENTER_VERTICAL, 0, 0);
mytoast.setDuration(Toast.LENGTH_SHORT);
mytoast.show();
Then I want to put it here:
public class DoPost extends AsyncTask<String, Void, Boolean>
{
Exception exception = null;
Context mContext = null;
. . . . .
public DoPost(Context context, String username, String password,
String reportcode, String remarks, String date, String province,
String infotype, String competitor, ArrayList<String> brands,
ArrayList<String> segments)
{
mContext = context;
. . . .
databaseHandler = new DatabaseHandler(context);
if (databaseHandler != null)
{
databaseHandler.close();
databaseHandler.createDB();
}
}
protected void onPreExecute()
{
progressDialog = new ProgressDialog(mContext);
progressDialog.setMessage("Uploading attachment details....");
progressDialog.show();
progressDialog.setCancelable(false);
}
#Override
protected Boolean doInBackground(String... arg0)
{
try {
JSONObject jObject = new JSONObject();
Log.d("DoPost Constants.FILE_URI", Constants.FILE_URI.toString());
Log.d("DoPost create SELECTEDFILE URI", SelectedFiles.listFileUri.toString());
Log.d("DoPost create SELECTEDFILE FILENAME", SelectedFiles.listFileName.toString());
// String filename = "Chapt-19.pdf";
String filename = "";
try {
JSONArray jArraySubrands = new JSONArray();
JSONArray jArrayConsumerSegments = new JSONArray();
JSONArray jArrayReportUpload = new JSONArray();
for (int i = 0; i < Constants.SHARED_PREFERENCES_SUBBRANDS.size(); i++)
{
JSONObject brand = new JSONObject();
brand.put("Id", _brands.get(i));
jArraySubrands.put(brand);
}
for (int j = 0; j < Constants.SHARED_PREFERENCES_SEGMENTS.size(); j++)
{
JSONObject consumerSegments = new JSONObject();
consumerSegments.put("Id", _segments.get(j));
jArrayConsumerSegments.put(consumerSegments);
}
for (int i = 0; i < Constants.ARRAYLIST_FILENAME.size(); i++)
{
JSONObject jObjectReportUpload = new JSONObject();
filename = Constants.ARRAYLIST_FILENAME.get(i);
jObjectReportUpload.put("ReportUploadId", 0);
jObjectReportUpload.put("Filename", filename);
jObjectReportUpload.put("TempFilename", filename);
jObjectReportUpload.put("Description", "Image Testing");
jObjectReportUpload.put("ReportUploadTypeId", 1);
jObjectReportUpload.put("ReportId", 0);
jArrayReportUpload.put(jObjectReportUpload);
Log.d("filename: ", filename);
}
jObject.put("ReportId", 0);
jObject.put("ReportCode", _code);
jObject.put("Title", "Mobile Developer");
jObject.put("Remarks", _remarks);
jObject.put("DateObserved", _date);
jObject.put("ProvinceId", _province);
jObject.put("InformationTypeId", _infotype);
jObject.put("ReportTypeId", 1);
jObject.put("IsCompetitor", _competitor);
jObject.put("SubBrands", jArraySubrands);
jObject.put("ConsumerSegments", jArrayConsumerSegments);
jObject.put("ReportUploads", jArrayReportUpload);
} catch (Exception e)
{
e.printStackTrace();
}
ResponseHandler<String> resonseHandler = new BasicResponseHandler();
HttpParams httpParameters = new BasicHttpParams();
HttpConnectionParams.setConnectionTimeout(httpParameters, 15000);
HttpConnectionParams.setSoTimeout(httpParameters, 15000);
HttpPost httpPost = new HttpPost("http://phsjghhghghulchghg4.hgh.com:1214/api/reports");
HttpClient httpclient = new DefaultHttpClient(httpParameters);
httpPost.addHeader("Authorization","Basic "+ Base64.encodeToString((_username + ":" + _password).getBytes(),Base64.NO_WRAP));
httpPost.setHeader("Content-Type", "application/json");
httpPost.setHeader("Accept", "application/json");
httpPost.setEntity(new ByteArrayEntity(jObject.toString().getBytes(HTTP.UTF_8)));
String response = httpclient.execute(httpPost).toString();
Log.i("response: ", response);
Log.i("JSON", jObject.toString());
} catch (ClientProtocolException e)
{
e.printStackTrace();
Log.e("Header","ClientProtocolException in callWebService(). "+ e.getMessage());
error = String.valueOf(e);
return false;
}
catch (IOException e)
{
e.printStackTrace();
Log.e("Header","IOException in callWebService(). " + e.getMessage());
error = String.valueOf(e);
return false;
}
return true;
}
protected void onPostExecute(Boolean valid)
{
progressDialog.dismiss();
Log.d("RESULT", String.valueOf(valid));
if(valid){
//Customzize toast here.
new DoPost(mContext,_username, _password, _code, _remarks, _date, _province, _infotype,_competitor,_brands, _segments).execute();
}else{
//Customzize toast here.
}
}
I think I've found out what's going on. Your scope is wrong. currently your code is running in AsyncTask, not Activity! That's why you cannot use getAssets, getLayoutInflater, findViewById, getBaseContext. Create your AsyncTask in your xxxActivity. And use Your xxxActivity.this.findViewById, and so on.

Resources