Android Asynctask return problems - android-asynctask

I am facing a problem in value 'return' in Asynctask class in doInBackground method. I am getting an error, about 'missing return statement in below code.
`public class ForecastNetwork extends AsyncTask {
public final String TAG = ForecastNetwork.class.getSimpleName();
#Override
protected Void doInBackground(Void... params) {
HttpURLConnection urlConnection = null;
BufferedReader reader = null;
// Will contain the raw JSON response as a string.
String forecastJsonStr = null;
try {
// Construct the URL for the OpenWeatherMap query
// Possible parameters are avaiable at OWM's forecast API page, at
// http://openweathermap.org/API#forecast
URL url = new URL("http://api.openweathermap.org/data/2.5/forecast/daily?q=94043&mode=json&units=metric&cnt=7");
// Create the request to OpenWeatherMap, and open the connection
urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setRequestMethod("GET");
urlConnection.connect();
// Read the input stream into a String
InputStream inputStream = urlConnection.getInputStream();
StringBuffer buffer = new StringBuffer();
if (inputStream == null) {
// Nothing to do.
return null;
}
reader = new BufferedReader(new InputStreamReader(inputStream));
String line;
while ((line = reader.readLine()) != null) {
// Since it's JSON, adding a newline isn't necessary (it won't affect parsing)
// But it does make debugging a *lot* easier if you print out the completed
// buffer for debugging.
buffer.append(line + "\n");
}
if (buffer.length() == 0) {
// Stream was empty. No point in parsing.
return null;
}
forecastJsonStr = buffer.toString();
} catch (IOException e) {
Log.e(TAG, "Error ", e);
// If the code didn't successfully get the weather data, there's no point in attemping
// to parse it.
return null;
} finally {
if (urlConnection != null) {
urlConnection.disconnect();
}
if (reader != null) {
try {
reader.close();
} catch (final IOException e) {
Log.e(TAG, "Error closing stream", e);
}
}
}
}`
What Should I return at the end?

I assume that you forgot to return the processing result
forecastJsonStr = buffer.toString();
return forecastJsonStr;

Related

is it possible to read the content of the file present in the ftp server? [duplicate]

This is re-worded from a previous question (which was probably a bit unclear).
I want to download a text file via FTP from a remote server, read the contents of the text file into a string and then discard the file. I don't need to actually save the file.
I am using the Apache Commons library so I have:
import org.apache.commons.net.ftp.FTPClient;
Can anyone help please, without simply redirecting me to a page with lots of possible answers on?
Not going to do the work for you, but once you have your connection established, you can call retrieveFile and pass it an OutputStream. You can google around and find the rest...
FTPClient ftp = new FTPClient();
...
ByteArrayOutputStream myVar = new ByteArrayOutputStream();
ftp.retrieveFile("remoteFileName.txt", myVar);
ByteArrayOutputStream
retrieveFile
Normally I'd leave a comment asking 'What have you tried?'. But now I'm feeling more generous :-)
Here you go:
private void ftpDownload() {
FTPClient ftp = null;
try {
ftp = new FTPClient();
ftp.connect(mServer);
try {
int reply = ftp.getReplyCode();
if (!FTPReply.isPositiveCompletion(reply)) {
throw new Exception("Connect failed: " + ftp.getReplyString());
}
if (!ftp.login(mUser, mPassword)) {
throw new Exception("Login failed: " + ftp.getReplyString());
}
try {
ftp.enterLocalPassiveMode();
if (!ftp.setFileType(FTP.BINARY_FILE_TYPE)) {
Log.e(TAG, "Setting binary file type failed.");
}
transferFile(ftp);
} catch(Exception e) {
handleThrowable(e);
} finally {
if (!ftp.logout()) {
Log.e(TAG, "Logout failed.");
}
}
} catch(Exception e) {
handleThrowable(e);
} finally {
ftp.disconnect();
}
} catch(Exception e) {
handleThrowable(e);
}
}
private void transferFile(FTPClient ftp) throws Exception {
long fileSize = getFileSize(ftp, mFilePath);
InputStream is = retrieveFileStream(ftp, mFilePath);
downloadFile(is, buffer, fileSize);
is.close();
if (!ftp.completePendingCommand()) {
throw new Exception("Pending command failed: " + ftp.getReplyString());
}
}
private InputStream retrieveFileStream(FTPClient ftp, String filePath)
throws Exception {
InputStream is = ftp.retrieveFileStream(filePath);
int reply = ftp.getReplyCode();
if (is == null
|| (!FTPReply.isPositivePreliminary(reply)
&& !FTPReply.isPositiveCompletion(reply))) {
throw new Exception(ftp.getReplyString());
}
return is;
}
private byte[] downloadFile(InputStream is, long fileSize)
throws Exception {
byte[] buffer = new byte[fileSize];
if (is.read(buffer, 0, buffer.length)) == -1) {
return null;
}
return buffer; // <-- Here is your file's contents !!!
}
private long getFileSize(FTPClient ftp, String filePath) throws Exception {
long fileSize = 0;
FTPFile[] files = ftp.listFiles(filePath);
if (files.length == 1 && files[0].isFile()) {
fileSize = files[0].getSize();
}
Log.i(TAG, "File size = " + fileSize);
return fileSize;
}
You can just skip the download to local filesystem part and do:
FTPClient ftpClient = new FTPClient();
try {
ftpClient.connect(server, port);
ftpClient.login(user, pass);
ftpClient.enterLocalPassiveMode();
ftpClient.setFileType(FTP.BINARY_FILE_TYPE);
InputStream inputStream = ftpClient.retrieveFileStream("/folder/file.dat");
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream, "Cp1252"));
while(reader.ready()) {
System.out.println(reader.readLine()); // Or whatever
}
inputStream.close();
} catch (IOException ex) {
ex.printStackTrace();
} finally {
try {
if (ftpClient.isConnected()) {
ftpClient.logout();
ftpClient.disconnect();
}
} catch (IOException ex) {
ex.printStackTrace();
}
}

Cannot invoke "org.apache.commons.logging.Log.isDebugEnabled()" because "this.logger" is null

Here the code that I used to save data and I use #Transactional. I want to write a test for this method, but it fails.
#Transactional(rollbackFor = BadRequestException.class, propagation = Propagation.REQUIRES_NEW)
public void saveContent(ContentAbstractEntity content) {
mongoTemplate.setSessionSynchronization(SessionSynchronization.ALWAYS);
TransactionBody txnBody =
(() -> {
ContentAbstractEntity contentAbstractEntity = contentRepository.save(content);
if (content instanceof LearningContent) {
LearningContent learningContent = (LearningContent) content;
Long tutorCountInDB = tutorRepository.countBy_idIn(learningContent.getTutorIds());
if (!countryRepository.existsBySyllabuses_grades_subjects__id(
learningContent.getSubjectId()))
throw new BadRequestException("Subject is not found");
Topic topic = topicRepository.findBy_id(learningContent.getTopicId());
if (topic == null) throw new BadRequestException("Topic is not found");
List<ObjectId> lessonIds =
topic.getLessons().stream().map(m -> m.get_id()).collect(Collectors.toList());
boolean allLessonsExists =
learningContent.getLessonIds().stream().allMatch(a -> lessonIds.contains(a));
if (!allLessonsExists) throw new BadRequestException("Lessons are not mismatched");
if (tutorCountInDB != learningContent.getTutorIds().size()) {
throw new BadRequestException("Tutors are not matched");
}
}
return "Successfully inserted";
});
MongoClient client = MongoClients.create(uri);
ClientSession clientSession = client.startSession();
try {
clientSession.withTransaction(txnBody);
} catch (BadRequestException e) {
throw new BadRequestException(e.getMessage());
} finally {
clientSession.close();
}
}
I tried to write a test for the above code, but it returns an error
#Test
void whenSaveContent() throws Exception {
ContentAbstractDto contentAbstractDto = new ContentAbstractDto();
ContentAbstractEntity content = learningVideo();
if (contentAbstractDto instanceof LearningDocsDto) {
LearningDocsDto learninfDocsDto = (LearningDocsDto) contentAbstractDto;
// ToDo when a Doc Saves and Assessment saves
}
when(contentRepository.save(content)).thenReturn(content);
if (content instanceof LearningContent) {
LearningContent learningContent = (LearningContent) content;
Long tutorCountInDB = (long) learningContent.getTutorIds().size();
when(tutorRepository.countBy_idIn(learningContent.getTutorIds())).thenReturn(tutorCountInDB);
when(subjectRepository.existsBy_id(learningContent.getSubjectId())).thenReturn(true);
Topic topic = getTopic();
when(topicRepository.findBy_id(learningContent.getTopicId())).thenReturn(topic);
if (topic == null) throw new BadRequestException("Topic is not found");
List<ObjectId> lessonIds =
topic.getLessons().stream().map(m -> m.get_id()).collect(Collectors.toList());
boolean allLessonsExists =
learningContent.getLessonIds().stream().allMatch(a -> lessonIds.contains(a));
if (!allLessonsExists) throw new BadRequestException("Lessons are not mismatched");
if (tutorCountInDB != learningContent.getTutorIds().size()) {
throw new BadRequestException("Tutors are not matched");
}
}

Get document from GET request

I need your help:
I have the following method
#Path("/download")
public class FileDownloadService {
#GET
public Response downloadFile(#QueryParam("filenet_id") String filenet_id, #QueryParam("version") String version) {
...
Document document = (Document) cmisObject;
return Response.ok(document, MediaType.APPLICATION_OCTET_STREAM).build();
}
and I want to get the document throught HTTP GET, I tried to write this code but I don't know how to get it, "output" don't conatains it:
URIBuilder builder = new URIBuilder();
builder.setScheme("http").setHost("localhost:8080").setPath("/filenetintegration/rest/download")
.setParameter("filenet_id", filenet_id)
.setParameter("version", version+".0");
URI uri = builder.build();
HttpGet httpget = new HttpGet(uri);
System.out.println(httpget.getURI());
HttpURLConnection urlConnection = (HttpURLConnection) new URL(uri.toString()).openConnection();
urlConnection.connect();
BufferedReader br = new BufferedReader(new InputStreamReader((urlConnection.getInputStream())));
String output;
while ((output = br.readLine()) != null) {
System.out.println(output);
}
Edit:
maybe the problem is on this line, it don't put the document inside the response:
return Response.ok(document, MediaType.APPLICATION_OCTET_STREAM).build();
You need something like this on the server side:
Document document = (Document) cmisObject;
ContentStream contentStream = document.getContentStream();
final InputStream stream = contentStream.getStream();
StreamingOutput output = (OutputStream out) -> {
try {
int b;
byte[] buffer = new byte[64*1024];
while ((b = stream.read(buffer)) > -1) {
out.write(buffer, 0, b);
}
} finally {
try {
stream.close();
} catch (IOException ioe) {}
}
};
return Response.ok(output, contentStream.getMimeType()).build();

How can I start AsyncTask's doInBackground repeatedly when I start the 'A activity'? [complete]

I make the HttpURLConnection to get data from MySQL (android+jsp+MySQL) in my android's AsyncTask.
when I start 'A activity', the first is OK. I can start doInBackground. but when I start the 'A activity' next, I can't start doInBackgound when I start 'A activity' repeatedly.
I want to start doInBackground whenever I start the 'A activity' repeatedly.
because I get data from MySQL in doInBackground.
I used to "task.cancel(true)" but this not working.
I'm nuwbe in android, please tell me how to start doInBackground repeatedly.
thank advance.
behind is my code.
oncreate code
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_confirm_inventory);
...........
connectJSP = new getInventoryFromMySQL();
connectJSP.execute();
...........
}
onBackPressed code
#Override
public void onBackPressed() {
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
if (drawer.isDrawerOpen(GravityCompat.END)) {
drawer.closeDrawer(GravityCompat.END);
} else {
connectJSP.cancel(true);
super.onBackPressed();
}
}
AsyncTask code
private class getInventoryFromMySQL extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... sId) {
String sResult = "Error";
try {
//URL setting and access
URL url = new URL("http://-----.com/*****.jsp");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
//setting
conn.setRequestMethod("POST");
// connection values
String sendBicycleName = bicycleName;
String sendBicycleYear = bicycleYear;
//StringBuffer
StringBuffer buffer = new StringBuffer();
buffer.append("sendBicycleName").append("=").append(sendBicycleName).append("&");
buffer.append("sendBicycleYear").append("=").append(sendBicycleYear);
//put data into JSP
OutputStreamWriter osw = new OutputStreamWriter(conn.getOutputStream(), "UTF-8");
osw.write(buffer.toString());
osw.flush();
//get data from JSP
InputStreamReader tmp = new InputStreamReader(conn.getInputStream(), "UTF-8");
BufferedReader reader = new BufferedReader(tmp);
String str;
//fit the order with JSP(garbage values)
reader.readLine(); reader.readLine(); reader.readLine(); reader.readLine();
//get data from JSP
for(;;) {
if((str = reader.readLine()) != null && (str != "") && (str != " ") && (str != "null")) {
mysqlStoreId[countInventory] = str;
for(int c=0; c<5; c++) {
for(int s=0; s<8; s++) {
str = reader.readLine();
mysqlInventory[countInventory][c][s] = Integer.parseInt(str);
}
}
countInventory++;
} else if(str == null && str == "null") {
//finish for if values equals null
break;
}
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return sResult;
}
}
I find the answer. I check all code's log.
the problem is that 'doInBackground' have an error. there is no an else in 'for(;;)' so AsyncTack make 'onCancelled()'. but I'm not write the 'onCancelled()' code.
when I add onCancelled(), I can cancel(true) and re-start the Asynctask.
Thank!

BlackBerry - Downloaded images are corrupted on wifi with HttpConnection

In my app I need to download several images from a server. I use this code to get a byte array :
HttpConnection connection = null;
InputStream inputStream = null;
byte[] data = null;
try
{
//connection = (HttpConnection)Connector.open(url);
connection = (HttpConnection)Connector.open(url, Connector.READ_WRITE, true);
int responseCode = connection.getResponseCode();
if(responseCode == HttpConnection.HTTP_OK)
{
inputStream = connection.openInputStream();
data = IOUtilities.streamToBytes(inputStream);
inputStream.close();
}
connection.close();
return data;
}
catch(IOException e)
{
return null;
}
The url are formed with the suffix ";deviceSide=false;ConnectionType=MDS - public" (without spaces) and it is working perfectly well.
The problem is that with phones that do not have a sim card, we can't connect to the internet via the MDS server. So we changed to use the connection factory and let BB choose whatever he wants :
ConnectionFactory connFact = new ConnectionFactory();
ConnectionDescriptor connDesc;
connDesc = connFact.getConnection(url);
if (connDesc != null)
{
final HttpConnection httpConn;
httpConn = (HttpConnection)connDesc.getConnection();
try
{
httpConn.setRequestMethod(HttpConnection.GET);
final int iResponseCode = httpConn.getResponseCode();
if(iResponseCode == HttpConnection.HTTP_OK)
{
InputStream inputStream = null;
try{
inputStream = httpConn.openInputStream();
byte[] data = IOUtilities.streamToBytes(inputStream);
return data;
}
catch(Exception e)
{
e.printStackTrace();
return null;
}
finally{
try
{
inputStream.close();
} catch (IOException e)
{
e.printStackTrace();
return null;
}
}
}
}
catch (IOException e)
{
System.err.println("Caught IOException: " + e.getMessage());
}
}
return null;
The connection works because it select the good prefix (interface=wifi in our case), but this create another problem.
Some images are not well downloaded, some of them (not the sames at each try) are corrupted, but only when the phone use a wifi connection to get these images.
How can I avoid this problem ? What method to get a connection do I have to use ? Is it possible to check if the user have a sim card in orderto use MDS - public ?
Here is an example of a corrupted image :
error image http://nsa30.casimages.com/img/2012/06/28/120628033716123822.png
try this:
public static String buildURL(String url) {
String connParams = "";
if (WLANInfo.getWLANState() == WLANInfo.WLAN_STATE_CONNECTED) {
connParams = ";interface=wifi"; //Connected to a WiFi access point.
} else {
int coverageStatus = CoverageInfo.getCoverageStatus();
//
if ((coverageStatus & CoverageInfo.COVERAGE_BIS_B) == CoverageInfo.COVERAGE_BIS_B) {
connParams = ";deviceside=false;ConnectionType=mds-public";
} else if ((coverageStatus & CoverageInfo.COVERAGE_DIRECT) == CoverageInfo.COVERAGE_DIRECT) {
// Have network coverage and a WAP 2.0 service book record
ServiceRecord record = getWAP2ServiceRecord();
//
if (record != null) {
connParams = ";deviceside=true;ConnectionUID=" + record.getUid();
} else {
connParams = ";deviceside=true";
}
} else if ((coverageStatus & CoverageInfo.COVERAGE_MDS) == CoverageInfo.COVERAGE_MDS) {
// Have an MDS service book and network coverage
connParams = ";deviceside=false";
}
}
Log.d("connection param"+url+connParams);
//
return url+connParams;
}
private static ServiceRecord getWAP2ServiceRecord() {
String cid;
String uid;
ServiceBook sb = ServiceBook.getSB();
ServiceRecord[] records = sb.getRecords();
//
for (int i = records.length -1; i >= 0; i--) {
cid = records[i].getCid().toLowerCase();
uid = records[i].getUid().toLowerCase();
//
if (cid.indexOf("wptcp") != -1
&& records[i].getUid().toLowerCase().indexOf("wap2") !=-1
&& uid.indexOf("wifi") == -1
&& uid.indexOf("mms") == -1) {
return records[i];
}
}
//
return null;
}
What happens when you append interface=wifi? Can you run the network diagnostic tool attached to below kb article and run all tests with SIM removed
http://supportforums.blackberry.com/t5/Java-Development/What-Is-Network-API-alternative-for-legacy-OS/ta-p/614822
Please also note that when download large files over BES/MDS there are limits imposed by MDS. Please ensure you review the below kb article
http://supportforums.blackberry.com/t5/Java-Development/Download-large-files-using-the-BlackBerry-Mobile-Data-System/ta-p/44585
You can check to see if coverage is sufficient for BIS_B (MDS public) but that won't help you if you are trying to support SIM-less users. I wonder if the problem is in an incomparability between the connection on Wi-Fi and IOUtilities.streamToBytes(). Try coding as recommended in the API documents.

Resources