Video is not playing using mediaplayer and surfaceview - android-mediaplayer

public class PlayVideoActivity extends Activity implements SurfaceHolder.Callback {
SurfaceView surfaceView;
SurfaceHolder surfaceHolder;
MediaPlayer mediaPlayer;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_play_video);
Intent intent=getIntent();
int no=intent.getIntExtra("index",0);
Toast.makeText(getBaseContext(),"Hello",Toast.LENGTH_SHORT).show();
getWindow().setFormat(PixelFormat.UNKNOWN);
surfaceView = (SurfaceView) findViewById(R.id.surfaceView1);
surfaceHolder = surfaceView.getHolder();
surfaceHolder.addCallback(this);
surfaceHolder.setFixedSize(176, 144);
surfaceHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
mediaPlayer = new MediaPlayer();
mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
mediaPlayer.setDisplay(surfaceHolder);
try {
mediaPlayer.setDataSource(MainActivity.musicPath[no]);
} catch (IllegalArgumentException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SecurityException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalStateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
mediaPlayer.prepare();
} catch (IllegalStateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
mediaPlayer.start();
}
I'm trying to play video using mediaplayer and surface view, but it is not playing,i writing my code here .please tell me the what is the problem in my code? thanks in advance
.......................................................................................................................................................................................

Related

Image not showing up in launch screen Android Studio

I have a project to do that involves downloading images from the internet with asyncTask with a progressbar at the bottom of the image and an infinite loop so it continues to through the images. When I run my code it says it was successful but the images are not showing up in the Android Emulator. If anyone could help that would great, thank you.
This is the code for mainActivity.java:
public class MainActivity extends AppCompatActivity {
String url = "https://cataas.com/cat";
private static XmlPullParser xpp;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ProgressBar progressBar = findViewById(R.id.progress_bar);
progressBar.setVisibility(View.VISIBLE);
progressBar.setProgress(0);
}
ImageView imageView;
public void Loading (View view) {
CatImages catImages = new CatImages();
imageView = findViewById(R.id.imgView);
try {
Bitmap bitmap = catImages.execute(url).get();
bitmap = catImages.execute(url).get();
imageView.setImageBitmap(bitmap);
} catch (ExecutionException e) {
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
class CatImages extends AsyncTask<String, Void, Bitmap> {
#Override
protected Bitmap doInBackground(String... strings) {
Bitmap bitmap = null;
URL url;
HttpURLConnection httpURLConnection;
InputStream in;
try {
url = new URL(strings[0]);
httpURLConnection = (HttpURLConnection)
url.openConnection();
in = httpURLConnection.getInputStream();
bitmap = BitmapFactory.decodeStream(in);
while (true) { }
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return bitmap;
}
}
}
enter code here

Create a Generic AttributeConverter[JDO] with JsonConverter

I´m using JDO + DataNucleus and implement a AttributeConverter with Jackson Json.
Already have a generic method for AttributeConverter:
#Override
public String convertToDatastore(ArrayList<Object> alist) {
String jsonString = null;
try {
jsonString = mapper.writeValueAsString(alist);
} catch (IOException e) {
e.printStackTrace();
}
return jsonString;
}
But, in Deserialize JSON to Object i read that i need to specify the class
public ArrayList<TelephoneNumber> convertToAttribute(String s) {
ArrayList<TelephoneNumber> obj = null;
try
{
obj = mapper.readValue(s, mapper.getTypeFactory().constructCollectionType(
List.class, TelephoneNumber.class));
}
catch (JsonParseException e) { e.printStackTrace();}
catch (JsonMappingException e) { e.printStackTrace(); }
catch (IOException e) { e.printStackTrace(); }
return obj;
}
but jsonString is a arrayList object
how can I do this?
thanks

How to re-use a mediaplayer after release() and null?

My app has a button which is playing a short mp3 file when clicked. I want to release and reuse the mediaplayer object properly (so it will not interfere other apps) when e.g. user gets a phone call, or home button is being clicked.
If I implement onPause and onStop this way:
#Override
public void onPause() {
super.onPause();
mp.release();
mp = null;
}
#Override
public void onStop() {
super.onStop();
mp.release();
mp = null;
}
then how do I re-use mp when onRestart is being called? is it the right way to do that? maybe I should use mp.stop()?
thanks
Edit: I found a solution myself. re-creating the object again:
#Override
publib void onResume() {
super.onResume();
mp = new MediaPlayer();
}
does the job. still a noob...:) thanks
Use onCompletion
#Override
public void onCompletion(MediaPlayer mp) {
// TODO Auto-generated method stub
myStereo.setLooping(true);
myStereo.release();
try {
myStereo.prepare();
} catch (IllegalStateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
myStereo.start();
}

J2ME -- failed to retrieve record from the RMS

i have been facing some problem with displaying the record from RMS. Im doing some e-wallet application for the j2me and here is my source code. it tell me that the recordwith#id has been added but I failed to retrieve and display the income amount from the users.
this the code for my RMS
//variable for record store
RecordStore ew_rs;
public static int addCount = 0;
public static int editCount = 0;
public static int deleteCount = 0;
public addIncome(){
this("tmpfile");
}
public addIncome(String filename) {
super();
try{
ew_rs = RecordStore.openRecordStore(filename, true);
ew_rs.addRecordListener(this);
} catch (RecordStoreException e){
e.printStackTrace();
}
}
public void closeRMS(){
try {
if (ew_rs.getNumRecords() > 0) {
ew_rs.closeRecordStore();
} else {
ew_rs.closeRecordStore();
RecordStore.deleteRecordStore(ew_rs.getName());
}
} catch (RecordStoreNotOpenException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (RecordStoreException e) {
e.printStackTrace();
}
}
//variable declaration for income adding
int ew_incomeID;
float ew_incomeAmount=0;
public addIncome(int incomeID, float incomeAmount){
this.ew_incomeID = incomeID;
this.ew_incomeAmount = incomeAmount;
}
public int getIncID(){
return ew_incomeID;
}
public void setIncID(int incomeID){
this.ew_incomeID = incomeID;
}
public float getIncAmt(){
return ew_incomeAmount;
}
public void setIncAmt(float incomeAmt){
this.ew_incomeAmount = incomeAmt;
}
public void recordAdded(RecordStore recordStore, int recordId) {
addCount++;
try {
System.out.println("Record with ID# " + recordId +
" added in Record Store " + recordStore.getName());
} catch (RecordStoreNotOpenException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public void recordChanged(RecordStore recordStore, int recordId) {
editCount++;
try {
System.out.println("Record with ID# " + recordId +
" changed in Record Store " + recordStore.getName());
} catch (RecordStoreNotOpenException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public void recordDeleted(RecordStore recordStore, int recordId) {
deleteCount++;
try {
System.out.println("Record with ID# " + recordId +
" deleted in Record Store " + recordStore.getName());
} catch (RecordStoreNotOpenException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
//add income
public void addIncomeFunction(int id , float IncAmt){
id = getIncID();
IncAmt = getIncAmt();
ByteArrayOutputStream baos = new ByteArrayOutputStream();
DataOutputStream out = new DataOutputStream(baos);
int convertAmt = Float.floatToIntBits(IncAmt);
try {
out.writeUTF(String.valueOf(id));
out.writeInt(convertAmt);
}catch (IOException e) {
e.printStackTrace();
}
byte[] b = baos.toByteArray();
try {
ew_rs.addRecord(b, 0, b.length);
} catch (RecordStoreException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally{
try {
baos.close();
out.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
//retrieve income
public byte[] getIncome(){
byte[] read = null;
try{
read = new byte[ew_rs.getSize()];
RecordEnumeration re = ew_rs.enumerateRecords(null, null, false);
ByteArrayInputStream bais = new ByteArrayInputStream(re.nextRecord());
DataInputStream in = new DataInputStream(bais);
for (int i = 0; i < re.numRecords() && re.hasNextElement(); i++) {
try {
in.readInt();
Float.intBitsToFloat(in.readInt());
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}catch (RecordStoreException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return read;
}
public RecordEnumeration enumerate(){
try {
return ew_rs.enumerateRecords(null, null, false);
} catch (RecordStoreNotOpenException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return null;
}
}
}
and the code for my display
MainMenu m;
addIncome income;
public Display d;
private static final Command cmdOk = new Command("Ok", Command.OK, 1);
private static final Command cmdBack = new Command("Back", Command.OK, 1);
public BalanceForm(MainMenu m){
this("Balance", m);
this.addCommand(cmdOk);
this.addCommand(cmdBack);
this.setCommandListener(this);
}
public BalanceForm(String arg0, MainMenu m){
super(arg0);
this.m = m;
}
public void prepareView(Display display){
this.setCommandListener(this);
this.d = display;
}
public void showView(){
d.setCurrent(this);
}
public void commandAction(Command c, Displayable d) {
if (c == cmdBack)
{
m.showMenu();
}
else{
byte[] b = income.getIncome();
ByteArrayInputStream bais = new ByteArrayInputStream(b);
DataInputStream in = new DataInputStream(bais);
try {
System.out.println(in.readInt());
System.out.println(in.readUTF());
//this.append(in.readUTF());
//this.append(String.valueOf(in.readInt()));
} catch (IOException e) {
//TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}

Fieldable.tokenStreamValue() returns null for tokenized field

I use lucene for N-Gram matching. I set a field to be analyzed using an N-Gram analyzer. I want to see how the tokens resulting from the analysis look like to make sure the n-grams are being correctly computed.
If I call the method Fieldable.tokenStreamValue() on the analyzed field of a document, I get null, while calling Fieldable.isTokenized() returns true.
I must add that the results of querying are consistent with n-grams being correctly generated.
Any explanations for this? I am essentially trying to do what is mentioned here:
How can I read a Lucene document field tokens after they are analyzed?
Here is the full code:
public class TestLuceneNgram {
public static class NGramQuery extends BooleanQuery {
public NGramQuery(final String queryTerm) throws IOException {
StringReader strReader = new StringReader(queryTerm);
TokenStream tokens = new NGramTokenizer(strReader);
CharTermAttribute termAtt = (CharTermAttribute) tokens
.addAttribute(CharTermAttribute.class);
while (tokens.incrementToken()) {
System.out.println(termAtt);
Term t = new Term("NGRAM_FIELD", termAtt.toString());
add(new TermQuery(t), BooleanClause.Occur.SHOULD);
}
}
}
public static class NGramSearcher extends IndexSearcher {
public NGramSearcher(final Directory directory)
throws CorruptIndexException, IOException {
super(IndexReader.open(directory));
}
public TopDocs search(final String term) {
try {
return search(new NGramQuery(term), 10);
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
}
public static class SubWordAnalyzer extends Analyzer {
#Override
public TokenStream tokenStream(final String fieldName,
final Reader reader) {
return new NGramTokenizer(reader);
}
}
public static Directory index(final String[] terms) {
Directory indexDirectory = new RAMDirectory();
IndexWriter indexWriter = null;
try {
indexWriter = new IndexWriter(indexDirectory,
new IndexWriterConfig(Version.LUCENE_32,
new SubWordAnalyzer()));
} catch (CorruptIndexException e) {
e.printStackTrace();
} catch (LockObtainFailedException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
for (int i = 0; i < terms.length; ++i) {
Document doc = new Document();
doc.add(new Field("NGRAM_FIELD", terms[i], Field.Store.YES,
Field.Index.ANALYZED,
Field.TermVector.WITH_POSITIONS_OFFSETS));
doc.add(new Field("ORIGINAL_FIELD", terms[i], Field.Store.YES,
Field.Index.NOT_ANALYZED));
try {
indexWriter.addDocument(doc);
} catch (CorruptIndexException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
try {
indexWriter.optimize();
} catch (CorruptIndexException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try {
indexWriter.close();
} catch (CorruptIndexException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return indexDirectory;
}
/**
* #param args
*/
public static void main(final String[] args) {
String[] terms = new String[] { "the first string", "the second one" };
Directory dir = index(terms);
NGramSearcher ngs = null;
try {
ngs = new NGramSearcher(dir);
} catch (CorruptIndexException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
TopDocs td = ngs.search("second");
System.out.println(td.totalHits);
for (ScoreDoc sd : td.scoreDocs) {
System.out.println(sd.doc + "---" + sd.score);
try {
System.out.println(ngs.doc(sd.doc).getFieldable("NGRAM_FIELD").
tokenStreamValue());
} catch (CorruptIndexException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
The first thing to check is whether you are actually storing this field at index time. If you're just indexing it, this is the expected result.