How to implement FragmentActivity as Fragment? - java

I'm new at making apps for Android and I'm now making my first app and I'm having issues.
I've successfully made myself a navigation drawer following this tutorial:
http://www.androidhive.info/2013/11/android-sliding-menu-using-navigation-drawer/
I have found this example which does exactly what I need - parsing XML and showing it as a list with images opening a more detailed view:
http://techiedreams.com/android-rss-reader-part-two-offline-reading-swipe-through-detail-views/
I have huge problems implementing the last example into my app (consisting of the first link) as the example uses a FragmentActivity while my app creates new Fragments from my MainActivity (I know FragmentActivity and Fragments are different).
How MainActivity creates new fragments:
private void displayView(int position) {
Fragment fragment = null;
switch (position) {
case 0:
fragment = new NewsFragment();
break; }
I need to make a Fragment consisting of what is inside of SplashActivity.
What would I need to do to implement SplashActivity into my MainActivity (and thus create a new Fragment of it)? Would I need to convert the FragmentActivity to a Fragment, or would I need to find a whole new solution?
If you would need and want to try it out yourself everything is available from the links above. As I'm a total beginner I really hope I can use the example above as it suits my app perfect.
SplashActivity:
public class SplashActivity extends Activity {
private String RSSFEEDURL = "http://www.nordichardware.se/feed/rss.html";
RSSFeed feed;
String fileName;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.splash);
fileName = "TDRSSFeed.td";
File feedFile = getBaseContext().getFileStreamPath(fileName);
ConnectivityManager conMgr = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
if (conMgr.getActiveNetworkInfo() == null) {
// No connectivity. Check if feed File exists
if (!feedFile.exists()) {
// No connectivity & Feed file doesn't exist: Show alert to exit
// & check for connectivity
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setMessage(
"Unable to reach server, \nPlease check your connectivity.")
.setTitle("TD RSS Reader")
.setCancelable(false)
.setPositiveButton("Exit",
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog,
int id) {
finish();
}
});
AlertDialog alert = builder.create();
alert.show();
} else {
// No connectivty and file exists: Read feed from the File
Toast toast = Toast.makeText(this,
"No connectivity! Reading last update...",
Toast.LENGTH_LONG);
toast.show();
feed = ReadFeed(fileName);
startLisActivity(feed);
}
} else {
// Connected - Start parsing
new AsyncLoadXMLFeed().execute();
}
}
private void startLisActivity(RSSFeed feed) {
Bundle bundle = new Bundle();
bundle.putSerializable("feed", feed);
// launch List activity
Intent intent = new Intent(SplashActivity.this, ListActivity.class);
intent.putExtras(bundle);
startActivity(intent);
// kill this activity
finish();
}
private class AsyncLoadXMLFeed extends AsyncTask<Void, Void, Void> {
#Override
protected Void doInBackground(Void... params) {
// Obtain feed
DOMParser myParser = new DOMParser();
feed = myParser.parseXml(RSSFEEDURL);
if (feed != null && feed.getItemCount() > 0)
WriteFeed(feed);
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
startLisActivity(feed);
}
}
// Method to write the feed to the File
private void WriteFeed(RSSFeed data) {
FileOutputStream fOut = null;
ObjectOutputStream osw = null;
try {
fOut = openFileOutput(fileName, MODE_PRIVATE);
osw = new ObjectOutputStream(fOut);
osw.writeObject(data);
osw.flush();
}
catch (Exception e) {
e.printStackTrace();
}
finally {
try {
fOut.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
// Method to read the feed from the File
private RSSFeed ReadFeed(String fName) {
FileInputStream fIn = null;
ObjectInputStream isr = null;
RSSFeed _feed = null;
File feedFile = getBaseContext().getFileStreamPath(fileName);
if (!feedFile.exists())
return null;
try {
fIn = openFileInput(fName);
isr = new ObjectInputStream(fIn);
_feed = (RSSFeed) isr.readObject();
}
catch (Exception e) {
e.printStackTrace();
}
finally {
try {
fIn.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return _feed;
}
}

If you want to create a fragment you have to extend the fragment class.
public class SplashActivity extends Fragment{
//your fragment code.
}
//Also you need to actually use the fragment to do this you can create an intent and start the intent or you can try
FragmentTransaction transaction = getFragmentManager().beginTransaction();
transaction.replace(R.id.fragment_container, newFragment);

Related

Android Translation application using yandex api showing result in emulator text view but not in real device

I am trying to make a translation application from English to Bangla using Yandex API.
It works fine in the emulator but in the real device it shows result for only one word in the text view but when writing a sentence it shows null / nothing.
I think the problem is buffer overflow but don't know how to fix it for the real device. Here are some reference pictures. In the emulator the result works fine:
In the real device it shows empty in text view:
But it works fine when a single word is used in real device.
Here is the code for my Asynctask:
public class
TranslatorBackgroundTask extends AsyncTask<String, Void, String> {
//Declare Context
Context ctx;
//Set Context
TranslatorBackgroundTask(Context ctx){
this.ctx = ctx;
}
String resultString;
#Override
protected String doInBackground(String... params) {
//String variables
String textToBeTranslated = params[0];
String languagePair = params[1];
String jsonString;
try {
//Set up the translation call URL
String yandexKey = "trnsl.1.1.20170823T130435Z.79a583874abfc8ff.61e23593359fdc92452e69a3d5ec05347fc4180b";
String yandexUrl = "https://translate.yandex.net/api/v1.5/tr.json/translate?key=" + yandexKey
+ "&text=" + textToBeTranslated + "&lang=" + languagePair;
URL yandexTranslateURL = new URL(yandexUrl);
//Set Http Conncection, Input Stream, and Buffered Reader
HttpURLConnection httpJsonConnection = (HttpURLConnection) yandexTranslateURL.openConnection();
InputStream inputStream = httpJsonConnection.getInputStream();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
//Set string builder and insert retrieved JSON result into it
StringBuilder jsonStringBuilder = new StringBuilder();
while ((jsonString = bufferedReader.readLine()) != null) {
jsonStringBuilder.append(jsonString + "\n");
}
//Close and disconnect
try {
bufferedReader.close();
} catch (IOException e) {
e.printStackTrace();
}
inputStream.close();
httpJsonConnection.disconnect();
//Making result human readable
resultString = jsonStringBuilder.toString().trim();
//Getting the characters between [ and ]
resultString = resultString.substring(resultString.indexOf('[')+1);
resultString = resultString.substring(0,resultString.indexOf("]"));
//Getting the characters between " and "
resultString = resultString.substring(resultString.indexOf("\"")+1);
resultString = resultString.substring(0,resultString.indexOf("\""));
Log.d("Translation Result:", resultString);
return jsonStringBuilder.toString().trim();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
//String text = String.valueOf(resultString);
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected void onPostExecute(String result) {
MainActivity.tvTranslatedText.setText(resultString);
Toast.makeText(ctx, resultString, Toast.LENGTH_LONG).show();
super.onPostExecute(result);
}
#Override
protected void onProgressUpdate(Void... values) {
super.onProgressUpdate(values);
}
}
And the code for the main activity:
public class MainActivity extends AppCompatActivity{
Context context=this;
private static final int REQUEST_CODE = 1234;
static TextView tvTranslatedText;
EditText etUserText;
Button buTranslate;
Button buSpeak;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.layout_activity_main);
tvTranslatedText = (TextView)findViewById(R.id.tvTranslatedText);
etUserText = (EditText)findViewById(R.id.etUserText);
buTranslate = (Button)findViewById(R.id.buTranslate);
buSpeak = (Button)findViewById(R.id.buSpeak);
}
public void buTranslate(View view) {
//Default variables for translation
String textToBeTranslated = "";
textToBeTranslated= etUserText.getText().toString();
String languagePair = "en-bn"; //English to bengali ("<source_language>-<target_language>")
//Executing the translation function
Translate(textToBeTranslated,languagePair);
}
//Function for calling executing the Translator Background Task
void Translate(String textToBeTranslated, String languagePair){
TranslatorBackgroundTask translatorBackgroundTask= new TranslatorBackgroundTask(context);
String translationResult = "";
translationResult = String.valueOf(translatorBackgroundTask.execute(textToBeTranslated,languagePair)); // Returns the translated text as a String
Log.d("Translation Result",translationResult); // Logs the result in Android Monitor
}
//Speak button activities
public void buSpeak(View view) {
startVoiceRecognitionActivity();
}
private void startVoiceRecognitionActivity()
{
Intent intent = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL,
RecognizerIntent.LANGUAGE_MODEL_FREE_FORM);
intent.putExtra(RecognizerIntent.EXTRA_PROMPT, "Speak to translate");
startActivityForResult(intent, REQUEST_CODE);
}
/**
* Handle the results from the voice recognition activity.
*/
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == REQUEST_CODE && resultCode == RESULT_OK) {
if (data != null) {
//pull all of the matches
ArrayList<String> matches = data.getStringArrayListExtra(RecognizerIntent.EXTRA_RESULTS);
String topResult = matches.get(0);
EditText AutoText = (EditText) findViewById(R.id.etUserText);
AutoText.setText(topResult);
}
}
}
}
The error message:
Caused by: com.google.android.apps.gsa.shared.exception.GsaIOException: Error code: 393238 | Buffer overflow, no available space.
Why didn't you add a listener to your sample code?
Try adding these on onCreate in MainActivity:
buTranslate.setOnClickListener(
new View.OnClickListener() {
#Override
public void onClick(View view) {
buTranslate(view);
}
}
);
Update:
There was another issue. Emulators on android sdk 16 don't show Unicode properly. Thats why you don't see your results, as those are Unicodes. Try Log to print your resultString.

How to show a progress bar during the creation of a file?

How can I show a progress bar when I click a button during the creation of a PDF file and hide it when I finished creating the file?
public class TwoFragment extends android.support.v4.app.Fragment {
private View v;
Intent chooser=null;
String myInt="";
String ciao="";
private String string="";
private ProgressBar pdfProgress;
ProgressTask task;
public TwoFragment() {
// Required empty public constructor
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View rootView = inflater.inflate(R.layout.fragment_two, container, false);
Button mButton = (Button) rootView.findViewById(R.id.newbutton);
mButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
//sendemail();
// pdfProgress.setVisibility(View.GONE);
/* pdfProgress.setVisibility(View.VISIBLE);
createPDF();
pdfProgress.setVisibility(View.GONE);
viewPDF();*/
/*MyAsyncTask myTask = new MyAsyncTask();
myTask.execute();
*/
showProgress();
}
});
TextView titolo3 = (TextView)rootView.findViewById(R.id.result);
TextView titolo2 = (TextView)rootView.findViewById(R.id.result2);
TextView titolo4 = (TextView)rootView.findViewById(R.id.resultpizze);
pdfProgress = (ProgressBar)rootView.findViewById(R.id.progressbar);
pdfProgress.setVisibility(View.GONE);
//pdfProgress.setVisibility(View.INVISIBLE);
//TextView titolo = (TextView)rootView.findViewById(R.id.quantità3);
/* class MyAsyncTask extends AsyncTask<Void, Void, Void> {
#Override
protected Void doInBackground(Void... params) {
// This runs in new thread!!!
// Always run long operations in another thread, so GUI will never be blocked
createPDF();
return null;
}
#Override
protected void onPostExecute(Void v) {
// This runs in MAIN thread, after the job's done.
// You always have to update gui from main thread
pdfProgress.setVisibility(View.GONE);
viewPDF();
}
}
*/
Bundle bundle2=getArguments();
if(bundle2 != null){
string = bundle2.getString("scelta2");
titolo3.setText(string);
}
/* Bundle bundle2=getArguments();
if(bundle2 != null){
// myInt = bundle2.getString("scelta2",myInt);
cacca=bundle2.getString("result",null);
//cacca=myInt;
// Log.d("ciao",cacca);
titolo3.setText(cacca);
}*/
//titolo3.setText(myInt);
/* Bundle bundle3=getArguments();
if(bundle3 != null){
// String myInt3 = bundle3.getString("totalebirre", null);
// cazzo2=Integer.parseInt(myInt3);
int cazzo2=bundle3.getInt("totalebirre");
titolo2.setText(String.valueOf(cazzo2));
}
Bundle bundle=getArguments();
if(bundle != null){
// String myInt2 = bundle2.getString("totalepizze", null);
// cazzo=Integer.parseInt(myInt2);
//titolo2.setText(myInt2);
String string=bundle.getString("scelta3", null);
titolo4.setText(string);
}
*/
return rootView;
}
/* public void sendemail(){
Intent intent = new Intent(Intent.ACTION_SEND);
intent.setData(Uri.parse("mailto:"));
String[] to={"marco_marcoletto#hotmail.it"};
intent.putExtra(Intent.EXTRA_EMAIL,to);
intent.putExtra(Intent.EXTRA_SUBJECT, "ciao");
intent.putExtra(Intent.EXTRA_TEXT, "zao");
intent.setType("message/rfc822");
chooser=intent.createChooser(intent,"manda email");
startActivity(chooser);
}*/
//#TargetApi(Build.VERSION_CODES.M)
public void createPDF() {
Document doc = new Document();
try {
String path = Environment.getExternalStorageDirectory()
.getAbsolutePath() + "/droidText";
File dir = new File(path);
if (!dir.exists())
dir.mkdirs();
Log.d("PDFCreator", "PDF Path: " + path);
//File file = new File(dir, "sample.pdf");
File file = new File(dir, "salve.pdf");
FileOutputStream fOut = new FileOutputStream(file);
PdfWriter.getInstance(doc, fOut);
// open the document
doc.open();
ByteArrayOutputStream stream = new ByteArrayOutputStream();
Bitmap bitmap = BitmapFactory.decodeResource(getContext()
.getResources(), R.drawable.androtuto);
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, stream);
Image myImg = Image.getInstance(stream.toByteArray());
myImg.setAlignment(Image.MIDDLE);
// add image to document
doc.add(myImg);
Paragraph p1 = new Paragraph(string);
Font paraFont = new Font(Font.COURIER);
p1.setAlignment(Paragraph.ALIGN_CENTER);
p1.setFont(paraFont);
// add paragraph to document
doc.add(p1);
Paragraph p2 = new Paragraph("Bonjour Android Tuto");
Font paraFont2 = new Font(Font.COURIER, 14.0f, Color.GREEN);
p2.setAlignment(Paragraph.ALIGN_CENTER);
p2.setFont(paraFont2);
doc.add(p2);
stream = new ByteArrayOutputStream();
bitmap = BitmapFactory.decodeResource(getContext()
.getResources(), R.drawable.android);
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, stream);
myImg = Image.getInstance(stream.toByteArray());
myImg.setAlignment(Image.MIDDLE);
// add image to document
doc.add(myImg);
// set footer
Phrase footerText = new Phrase("Pied de page ");
HeaderFooter pdfFooter = new HeaderFooter(footerText, false);
doc.setFooter(pdfFooter);
} catch (DocumentException de) {
// Log.e("PDFCreator", "DocumentException:" + de);
Log.e("PDFCreator", "DocumentException:" + de.getMessage());
} catch (IOException e) {
// Log.e("PDFCreator", "ioException:" + e);
Log.e("PDFCreator", "DocumentException:" + e.getMessage());
} finally {
doc.close();
}
}
public void viewPDF(){
String path = "/sdcard/droidText/salve.pdf";
File targetFile = new File(path);
Uri targetUri = Uri.fromFile(targetFile);
Intent intent;
intent = new Intent(Intent.ACTION_VIEW);
intent.setDataAndType(targetUri, "application/pdf");
startActivity(intent);
}
private class ProgressTask extends AsyncTask<Integer,Integer,Void> {
protected void onPreExecute() {
pdfProgress.setMax(100); // set maximum progress to 100.
}
protected void onCancelled() {
pdfProgress.setMax(0); // stop the progress
}
protected Void doInBackground(Integer... params) {
int start=params[0];
for(int i=start;i<=100;i+=5){
try {
boolean cancelled=isCancelled();
if(!cancelled) {
publishProgress(i);
Log.v("Progress","increment " + i);
//onProgressUpdate(i);
SystemClock.sleep(1000);
}
createPDF();
} catch (Exception e) {
Log.e("Error", e.toString());
}
}
return null;
}
protected void onProgressUpdate(Integer... values) {
// increment progress bar by progress value
//setProgress(10);
}
protected void onPostExecute(Void result) {
// async task finished
Log.v("Progress", "Finished");
viewPDF();
}
}
public void showProgress() {
task = new ProgressTask();
// start progress bar with initial progress 10
///////////////////task.execute(10,10,null);
task.execute(10);
}
}
Define a ProgressDialog in your Fragment as follows. The following code will add a ProgessDialog; to update it to show a Progress Bar too, read this.
private ProgressDialog processingDialog;
Now, in your onClick()
mButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
processingDialog = ProgressDialog.show(this, "Creating PDF", "Please wait ...", true, false);
createPDF();
processingDialog.dismiss();
viewPDF();
}
});
This should do the task, however, I have some more recommendations for you. As creating a PDF (I assume) will be time consuming, it might not be a good idea to do it on the UI Thread. Instead, use an AsyncTask to generate your PDF in doInBackground(), show the ProgressDialog, and finally dismiss() it in onPostExecute().
This code will do what you want using AsyncTask which is reccomended way of doing this!
private class MakePDF extends AsyncTask<Void, Void, Void> {
private ProgressDialog processingDialog;
Context cnt = null;
MakePDF(Context cnt)
{
this.cnt = cnt;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
processingDialog = ProgressDialog.show( this.cnt, "Creating PDF", "Please wait ...", true, false);
}
#Override
protected Void doInBackground(Void... arg0) {
createPDF();
return null;
}
#Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
processingDialog.dismiss();
viewPDF();
}
}
Now call above AsyncTask using
new MakePDF(ActivityName.this).execute(); //here in constructor pass context of an calling activity.
from your activity class

Download PDF not working

In my application, I have an expandablelistview and I want to open a PDF downloaded from the internet when I click on a specific child. The problem is that the pdf file (Read.pdf) is always empty, meaning that the download is not working.
Downloader Class:
public class Downloader {
public static void DownloadFile(String fileURL, File directory) {
try {
FileOutputStream f = new FileOutputStream(directory);
URL u = new URL(fileURL);
HttpURLConnection c = (HttpURLConnection) u.openConnection();
c.setRequestMethod("GET");
c.setDoOutput(true);
c.connect();
InputStream in = c.getInputStream();
byte[] buffer = new byte[1024];
int len1 = 0;
while ((len1 = in.read(buffer)) > 0) {
f.write(buffer, 0, len1);
}
f.close();
} catch (Exception e) {
e.printStackTrace();
}
}
Part of the Activity:
private void registerClick() {
expListView.setOnChildClickListener(new OnChildClickListener() {
#Override
public boolean onChildClick(ExpandableListView parent, View v,
int groupPosition, int childPosition, long id) {
if ((groupPosition == 0) && (childPosition == 0)){
File file = new File(Environment.getExternalStorageDirectory()+File.separator+"IAVE", "Read.pdf");
try {
file.createNewFile();
} catch (IOException e1) {
e1.printStackTrace();
}
Downloader.DownloadFile("https://www.cp.pt/StaticFiles/Passageiros/1_horarios/horarios/PDF/lx/linha_cascais.pdf", file);
AbrirPDF.showPdf();
} else {
}
return false;
}
});
}
I think the OpenPDF (AbrirPDF) doesn't have any problem, but I will post it...
public class AbrirPDF {
public static void showPdf()
{
File file = new File(Environment.getExternalStorageDirectory()+File.separator+"IAVE/Read.pdf");
PackageManager packageManager = ContextGetter.getAppContext().getPackageManager();
Intent testIntent = new Intent(Intent.ACTION_VIEW);
testIntent.setType("application/pdf");
List list = packageManager.queryIntentActivities(testIntent, PackageManager.MATCH_DEFAULT_ONLY);
Intent intent = new Intent();
intent.setAction(Intent.ACTION_VIEW);
Uri uri = Uri.fromFile(file);
intent.setDataAndType(uri, "application/pdf");
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
ContextGetter.getAppContext().startActivity(intent);
}
}
Thank you.
Ideally, your download should happen in a separate thread to avoid locking your app.
Here is an example that also includes a progress bar.
public class MainActivity extends Activity {
private ProgressDialog pDialog;
public static final int progress_bar_type = 0;
private static String file_url = "https://www.cp.pt/StaticFiles/Passageiros/1_horarios/horarios/PDF/lx/linha_cascais.pdf";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
new DownloadFileFromURL().execute(file_url);
}
#Override
protected Dialog onCreateDialog(int id) {
switch (id) {
case progress_bar_type: // we set this to 0
pDialog = new ProgressDialog(this);
pDialog.setMessage("Downloading file. Please wait...");
pDialog.setIndeterminate(false);
pDialog.setMax(100);
pDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
pDialog.setCancelable(true);
pDialog.show();
return pDialog;
default:
return null;
}
}
class DownloadFileFromURL extends AsyncTask<String, String, String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
showDialog(progress_bar_type);
}
#Override
protected String doInBackground(String... f_url) {
int count;
try {
URL url = new URL(f_url[0]);
URLConnection conection = url.openConnection();
conection.connect();
// this will be useful so that you can show a tipical 0-100%
// progress bar
int lenghtOfFile = conection.getContentLength();
// download the file
InputStream input = new BufferedInputStream(url.openStream(),
8192);
// Output stream
OutputStream output = new FileOutputStream(Environment
.getExternalStorageDirectory().toString()
+ "/2011.kml");
byte data[] = new byte[1024];
long total = 0;
while ((count = input.read(data)) != -1) {
total += count;
// publishing the progress....
// After this onProgressUpdate will be called
publishProgress("" + (int) ((total * 100) / lenghtOfFile));
// writing data to file
output.write(data, 0, count);
}
// flushing output
output.flush();
// closing streams
output.close();
input.close();
} catch (Exception e) {
Log.e("Error: ", e.getMessage());
}
return null;
}
protected void onProgressUpdate(String... progress) {
// setting progress percentage
pDialog.setProgress(Integer.parseInt(progress[0]));
}
#Override
protected void onPostExecute(String file_url) {
// dismiss the dialog after the file was downloaded
dismissDialog(progress_bar_type);
}
}
}

Downloading list of audio from URL

So I'm implementing audio Playlist app that imports audios from Parse.com, and when I retrieve them by streaming them directly from their URls, it took maybe one minute to play after clicking play button.
So I don't want to use streaming from URL methods to play my audio from server because it makes it so slow. Instead I want to download list of audios from server (Parse.com) at once and then playing them by retrieving from sdcard.
I have the class that downloads single audio from single URL .. I want to edit the code to make it downloads more than one audio at once.
here is the class I have to download audio from URL.
class DownloadMusicfromInternet extends AsyncTask<String, String, String> {
private Context mContext;
private MediaPlayer mPlayer;
public DownloadMusicfromInternet(Context context) {
mContext = context;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
}
// Download Music File from Internet
#Override
protected String doInBackground(String... f_url) {
int count;
try {
URL url = new URL(f_url[0]);
URLConnection conection = url.openConnection();
conection.connect();
// Get Music file length
int lenghtOfFile = conection.getContentLength();
// input stream to read file - with 8k buffer
InputStream input = new BufferedInputStream(url.openStream(), 10 * 1024);
// Output stream to write file in SD card
OutputStream output = new
Also if you could help me in how to set a name for the audios, I don't want to write static name because I'm downloading more than one audio at a time .
FileOutputStream(Environment.getExternalStorageDirectory().getPath() + "/"+"how to put unique name for each audio here ?"+".mp3");
byte data[] = new byte[1024];
long total = 0;
while ((count = input.read(data)) != -1) {
total += count;
publishProgress("" + (int) ((total * 100) / lenghtOfFile));
// Write data to file
output.write(data, 0, count);
}
// Flush output
output.flush();
// Close streams
output.close();
input.close();
} catch (Exception e) {
Log.e("Error: ", e.getMessage());
}
return null;
}
// While Downloading Music File
// Once Music File is downloaded
#Override
protected void onPostExecute(String file_url) {
// Play the music
playMusic();
}
// Play Music
protected void playMusic() {
// Read Mp3 file present under SD card
Uri myUri1 = Uri.parse("file:///sdcard/"+"the same unique name that was set previously ! "+".mp3");
mPlayer = new MediaPlayer();
mPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
try {
mPlayer.setDataSource(mContext.getApplicationContext(), myUri1);
mPlayer.prepare();
// Start playing the Music file
mPlayer.start();
mPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
public void onCompletion(MediaPlayer mp) {
// TODO Auto-generated method stub
// Once Music is completed playing, enable the button
// btnPlayMusic.setEnabled(true);
Toast.makeText(mContext.getApplicationContext(), "Music completed playing", Toast.LENGTH_LONG).show();
}
});
} catch (IllegalArgumentException e) {
Toast.makeText(mContext.getApplicationContext(), "You might not set the URI correctly!", Toast.LENGTH_LONG).show();
} catch (SecurityException e) {
Toast.makeText(mContext.getApplicationContext(), "URI cannot be accessed, permissed needed", Toast.LENGTH_LONG).show();
} catch (IllegalStateException e) {
Toast.makeText(mContext.getApplicationContext(), "Media Player is not in correct state", Toast.LENGTH_LONG).show();
} catch (IOException e) {
Toast.makeText(mContext.getApplicationContext(), "IO Error occured", Toast.LENGTH_LONG).show();
}
}
}
and this is my adapter, and here is where my problem occurs and crashes my app. I don't know how to call ( DownloadMusicfromInternet ) more than once from the following adapter .
public class mAdapter extends ParseQueryAdapter<ParseObject> {
public mAdapter (Context context) {
super(context, new ParseQueryAdapter.QueryFactory<ParseObject>() {
public ParseQuery create() {
ParseQuery query = new ParseQuery("MusicPlaylist");
return query;
}
});
}
#Override
public View getItemView(final ParseObject object, View v, ViewGroup parent) {
if (v == null) {
v = View.inflate(getContext(), R.layout.list_music, null);
}
super.getItemView(object, v, parent);
//Audio retrieving
final ImageButton btn = (ImageButton) v.findViewById(R.id.play_btn);
final ParseFile fileObject = object.getParseFile("music");
**// here I put a loop because I want it to download a list of audios at once and I think here is the problem**
if (fileObject != null) {
for (int i = 10; i >= j; j++) {
new DownloadMusicfromInternet().execute(fileObject.getUrl());
}
fileObject.getDataInBackground(new GetDataCallback() {
#Override
public void done(byte[] bytes, com.parse.ParseException e) {
btn.setOnClickListener(new View.OnClickListener() {
public void onClick(View arg0) {
}//end on click
}//end listener
);
}//end done
});//end get data
}//end if
return v;
}//end getItem View
}//end mAdapter
Any help would be appreciated ..

Parsing Xml with Sax on Android

I'm trying to parse an XML from a url page. To do so I have used the SAX implementation explained in this IBM example with the Adapter and other changes I got from this article. I've also tried to implement an AsyncTask to do the parsing and show a ProgressDialog but I think this is where my application starts to break down.
I don't really know exactly how to implement the AsyncTask into my code, and I believe my poor implementation is causing my app to force close.
MainActivity:
public class MainActivity extends Activity {
/** Called when the activity is first created. */
ListView lv1;
ProgressDialog ShowProgress;
public static ArrayList<MangaItem> MangaItemList = new ArrayList<MangaItem>();
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
lv1 = (ListView) findViewById(R.id.listView1);
ShowProgress = ProgressDialog.show(MainActivity.this, "",
"Loading. Please wait...", true);
//new loadingTask().execute("http://www.mangapanda.com/alphabetical");
new loadFeedTask().execute();
lv1.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
Intent intent = new Intent(Intent.ACTION_VIEW).setData(Uri
.parse(MangaItemList.get(position).getMangaLink()));
startActivity(intent);
}
});
}
class loadFeedTask extends AsyncTask<String, Void, ArrayList<MangaItem>> {
private String feedUrl;
protected void onPostExecute(String s) {
lv1.setAdapter(new EfficientAdapter(MainActivity.this, MangaItemList));
//new MangaParserTask().execute();
ShowProgress.dismiss();
}
protected ArrayList<MangaItem> doInBackground(String... params) {
ArrayList<MangaItem> ParsedMangaItemList = new ArrayList<MangaItem>();
feedUrl = "http://www.mangapanda.com/alphabetical";
FeedParser parser = new SaxFeedParser(feedUrl);
ParsedMangaItemList = parser.parse();
for (MangaItem mitem : ParsedMangaItemList) {
MangaItemList.add(mitem);
}
return MangaItemList;
}
}
}
How can I properly use AsyncTask so that my parser will return an ArrayList that I can then put into an ArrayAdapter
Improper use of type parameters in subclass (AsyncTask<Params, Progress, Result>). Re-write the AsyncTask sub-class.
class loadFeedTask extends AsyncTask<String, Void, ArrayList<MangaItem>> {
protected void onPostExecute(ArrayList<MangaItem> list) {
lv1.setAdapter(new EfficientAdapter(MainActivity.this, list));
ShowProgress.dismiss();
}
protected ArrayList<MangaItem> doInBackground(String... params) {
ArrayList<MangaItem> list=null;
String feedUrl = "http://www.mangapanda.com/alphabetical";
FeedParser parser = new SaxFeedParser(feedUrl);
list = parser.parse();
MangaItemList=list;
return list;
}
}
use this code
try {
items = new ArrayList<String>();
XmlPullParserFactory factory = XmlPullParserFactory.newInstance();
factory.setNamespaceAware(true);
XmlPullParser xpp = factory.newPullParser();
xpp.setInput(new InputStreamReader(
getUrlData(" url")));
while (xpp.getEventType() != XmlPullParser.END_DOCUMENT) {
Log.i(TAG, "doc started");
if (xpp.getEventType() == XmlPullParser.START_TAG) {
if (xpp.getName().equals("entry")) {
items.add(xpp.getAttributeValue(0));
}
}
xpp.next();
}
} catch (Throwable t) {
Toast.makeText(this, "Request failed: " + t.toString(),
Toast.LENGTH_LONG).show();
}
get url data method
public InputStream getUrlData(String url) throws URISyntaxException,
ClientProtocolException, IOException {
DefaultHttpClient client = new DefaultHttpClient();
HttpGet method = new HttpGet(new URI(url));
HttpResponse res = client.execute(method);
return res.getEntity().getContent();
}

Categories

Resources