Setting Json Array in listview but while clicking on particular list item, listview get hang - arrays

I am parsing below jsong String and able to parse also and set in listview but while clicking on particular list item it get hang and doesn't fire any error or doesn't perform any action. What will be the possible solution for that?
thanks.
Json String
try {
output= httpObject.OpenHttpConnection(HomesUrl);
} catch (ProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
parseJsonResponse(output);
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
mEditorialList.setOnItemClickListener( new OnItemClickListener() {
public void onItemClick(AdapterView<?> arg0, View v,
int position, long id) {
System.out.println("clicked");
//Intent mEditorialIntent = new Intent(Homes.this, BrowseDetailsPage.class);
//startActivity(mEditorialIntent);
System.out.println("clicked");
}
});
parserClass:
public void parseJsonResponse(String output) throws JSONException {
// TODO Auto-generated method stub
if(output!=null){
try {
mFeaturedArraylist = new JSONArray();
mFeaturedArraylist=new JSONObject(output).getJSONObject("Data").getJSONArray("Featured");
for (int i = 0; i < mFeaturedArraylist.length(); i++) {
JSONObject headObject = mFeaturedArraylist.getJSONObject(i);
mTextViewHead.setText(headObject.optString("Title"));
}
mEditorialArraylist = new JSONArray();
mEditorialArraylist = new JSONObject(output).getJSONObject("Data").getJSONArray("Editorials");
globalAdapter = new EditorialAdapter(Homes.this, mEditorialArraylist);
mEditorialList.setAdapter(globalAdapter);
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
}
}
EditorialAdapter:
public class EditorialAdapter extends BaseAdapter{
private LayoutInflater mInflater;
JSONArray mEditorial;
public EditorialAdapter(Context context, JSONArray arrList){
mEditorial = arrList;
mInflater = LayoutInflater.from(context);
}
public int getCount() {
// TODO Auto-generated method stub
return mEditorial.length();
}
public Object getItem(int position) {
// TODO Auto-generated method stub
return position;
}
public long getItemId(int position) {
// TODO Auto-generated method stub
return position;
}
public class ViewHolder{
TextView twtdata;
ImageView twtimg;
TextView twtnm;
}
public View getView(int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
ViewHolder holder;
View vi= convertView;
if(convertView==null){
vi= mInflater.inflate(R.layout.home_listrow, null);
holder = new ViewHolder();
holder.twtdata = (TextView) vi.findViewById(R.id.txtlistby);
holder.twtnm = (TextView) vi.findViewById(R.id.txtlisttitle);
holder.twtimg = (ImageView) vi.findViewById(R.id.avatar);
vi.setTag(holder);
}
else{
holder = (ViewHolder) vi.getTag();
}
try {
JSONObject jObj = mEditorial.optJSONObject(position);
holder.twtnm.setText(jObj.getString("Title"));
holder.twtdata.setText("By "+jObj.getString("AuthorName"));
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return vi;
}
}

Related

Why do i never enter in specific callback functions in native interface?

I'm making an application which has to detect a bluetooth card reader and if a card is inserted or removed from this one.
I'm using an API for the android part in my native interface so I implement two callback functions from an interface which concerns the bluetooth card reader detection and two other callback functions which concerns the detection of cards in the bluetooth card reader.
Two callback functions which are called when the bluetooth card reader is detected and the two others which are called when a card is inserted or removed from the device.
I have no problem with the callback which are called when the bluetooth card reader is detected but the application never calls the functions which must be called when the card are inserted or removed.
public class FtReaderNativeImpl implements BluetoothRead.CardListener,BluetoothRead.ReaderListener{
private BluetoothRead btRead;
ArrayList<BluetoothDevice> listRead;
public String scanBluetooth(){
String chaine ="";
if (Looper.myLooper() == null)
{
Looper.prepare();
}
Log.p("btread avant init:"+btRead);
btRead = new
BluetoothRead(com.codename1.impl.android.AndroidNativeUtil.getContext());
btRead.setCardListener(this);
btRead.setReaderListener(this);
ReturnCode rc = btRead.btInitLib();
Log.p("btread après init:"+btRead);
Log.p("rc:"+rc);
return chaine;
}
#Override
public void CardInserted()
{
//showMessage("onCardInserted");
String chaine="";
//Toast.makeText(com.codename1.impl.android.AndroidNativeUtil.getActivity(), "INSERTED", Toast.LENGTH_SHORT).show();
chaine+=btRead.getName();
chaine+=btRead.getFirstName();
eidReader.showDialog("INSERTED "+chaine);
Log.p("btInsertOK");
}
#Override
public void CardRemoved()
{
String chaine="";
//Toast.makeText(com.codename1.impl.android.AndroidNativeUtil.getActivity(), "REMOVED", Toast.LENGTH_SHORT).show();
EidReader.showDialog("REMOVED "+chaine);
Log.p("btRemoveNOK");
}
#Override
public void ReaderConnected(BluetoothDevice bluetoothDevice)
{
/*Toast.makeText(com.codename1.impl.android.AndroidNativeUtil.getActivity(), "CONNECTED", Toast.LENGTH_SHORT).show();*/
EidReader.showDialog("CONNECTED");
Log.p("onReaderConnected: " + bluetoothDevice.getName());
if (btRead.btOpen(bluetoothDevice) == ReturnCode.OK) {
Log.p("btOpen OK");
} else {
Log.p("btOpen NOK");
}
Log.p("btread après listener:"+btRead);
}
#Override
public void ReaderDisconnected(BluetoothDevice bluetoothDevice)
{
//Toast.makeText(com.codename1.impl.android.AndroidNativeUtil.getActivity(), "DISCONNECTED", Toast.LENGTH_SHORT).show();
EidReader.showDialog("DISCONNECTED");
}}
ScanBluetooth is just a initialization method which is called in the beginning of the form:
public class EidReader extends Form implements HasLogger {
Container loggatt = new Container();
private Bluetooth bt;
private static Container devicesCnt;
private Map devices = new HashMap();
Form main = this;
FtReaderNative frn;
public EidReader(Form parent)
{
this.setLayout(new BoxLayout(BoxLayout.Y_AXIS));
Display dis = Display.getInstance();
frn = (FtReaderNative)NativeLookup.create(FtReaderNative.class);
if(dis.getPlatformName().compareTo("and")==0){
LocationManager lm = LocationManager.getLocationManager();
}
bt = new Bluetooth();
frn.scanBluetooth();
//combo.setRenderer(new GenericListCellRenderer<>(new MultiButton(),new MultiButton()));
this.add(new Button(new Command("enable bluetooth")
{
#Override
public void actionPerformed(ActionEvent evt){
try {
if (!bt.isEnabled()) {
bt.enable();
}
if (!bt.hasPermission()) {
bt.requestPermission();
}
} catch (IOException ex) {
ex.printStackTrace();
}
}
}));
this.add(new Button(new Command("initialize")
{
#Override
public void actionPerformed(ActionEvent evt)
{
try {
bt.initialize(true, false, "bluetoothleplugin");
} catch (IOException ex) {
ex.printStackTrace();
}
}
}));
Button bttest = new Button("DISPLAY READER");
bttest.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent ev)
{
DeleteUI();
StringTokenizer st = new StringTokenizer(frn.infoDevices());
while (st.hasMoreTokens()) {
MultiButton mb = new MultiButton(st.nextToken());
mb.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ev) {
devicesCnt.add(new SpanLabel(frn.readerStatus( mb.getTextLine1())));
}});
devicesCnt.add(mb);
}
}
});
this.add(bttest);
devicesCnt = new Container(new BoxLayout(BoxLayout.Y_AXIS));
devicesCnt.setScrollableY(true);
this.add(devicesCnt);
this.show();
}
private void DeleteUI()
{
devicesCnt.removeAll();
devicesCnt.revalidate();
}
#Override
public String getLogName()
{
// TODO Auto-generated method stub
return null;
}
public static void showDialog(String txt)
{
//Display.getInstance().callSerially(()->
//{
devicesCnt.add(new SpanLabel(txt));
devicesCnt.forceRevalidate();
//});
}
}

Can Async Task write in internal storage android?

Hi i need to download a file from url and save in internal storage,so the download process run in async task.
First, I have tried to write a string in a file with async task but give me error: Failed to create oat file.
The same code work without task, so my question is i must download the file in external storage and after move in internal?
private void writeInFile() {
FileOutputStream output = null;
String text = "TEXT";
try {
output = openFileOutput("nameFile.abc",Context.MODE_PRIVATE);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
try {
output.write(text.getBytes());
output.flush();
output.close();
} catch (IOException e) {
e.printStackTrace();
}
}
But if i call this function in doInBackground of class that extend AsyncTask i receive the error.
LicenzaTask mt = new LicenzaTask(this);
mt.execute();
public class LicenzaTask extends AsyncTask<Void, Void, Void> {
private Context mContext;
public LicenzaTask(MainActivity mainActivity) {
mContext = mainActivity;
}
#Override
protected Void doInBackground(Void... voids) {
modifyFile();
return null;
}
private void modifyFile() {
File file = new File(mContext.getFilesDir() + "nome.abc");
String text = "text";
BufferedWriter output = null;
try {
output = new BufferedWriter(new FileWriter(file));
output.write(text);
} catch (IOException e) {
e.printStackTrace();
} finally {
if (output != null) {
try {
output.close();
} catch (IOException e) {
}
}
}
}

Show toast if mp3 file there was not in SD card

In this class a mp3 file played from sd card, but if mp3 file not available
app give "force close"
i want cods that show toast if mp3 there was not in SD card(Not download) and back to previous activity.plase help me
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
getInit();
seekUpdation();
}
public void getInit() {
seek_bar = (SeekBar) findViewById(R.id.seek_bar);
play_button = (Button) findViewById(R.id.play_button);
pause_button = (Button) findViewById(R.id.pause_button);
text_shown = (TextView) findViewById(R.id.text_shown);
play_button.setOnClickListener(this);
pause_button.setOnClickListener(this);
String filePath = Environment.getExternalStorageDirectory() + "/Android/music.mp3";
mediaPlayer = new MediaPlayer();
try {
mediaPlayer.setDataSource(filePath);
} 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();
}
mediaPlayer.setOnPreparedListener(new OnPreparedListener() {
#Override
public void onPrepared(MediaPlayer mediaPlayer) {
}
});
mediaPlayer.prepareAsync();
seek_bar.setMax(mediaPlayer.getDuration());
}
Runnable run = new Runnable() {
#Override
public void run() {
seekUpdation();
}
};
public void seekUpdation() {
seek_bar.setProgress(mediaPlayer.getCurrentPosition());
seekHandler.postDelayed(run, 1000);
seek_bar.setOnSeekBarChangeListener(new OnSeekBarChangeListener() {
#Override
public void onStopTrackingTouch(SeekBar seek_bar) {
// TODO Auto-generated method stub
}
#Override
public void onStartTrackingTouch(SeekBar seek_bar) {
// TODO Auto-generated method stub
}
#Override
public void onProgressChanged(SeekBar seek_bar, int progress, boolean fromUser) {
if(fromUser){
mediaPlayer.seekTo(progress);
seek_bar.setProgress(progress);
}
}
});
}
#Override
public void onClick(View view) {
switch (view.getId()) {
case R.id.play_button:
text_shown.setText("Playing...");
mediaPlayer.start();
break;
case R.id.pause_button:
mediaPlayer.pause();
text_shown.setText("Paused...");
}
}
public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
if(fromUser){
mediaPlayer.seekTo(progress);
seekBar.setProgress(progress);
}
}
In IOException catch block place this code:
Toast.makeText(context,'No mp3 file found',Toast.LENGTH_SHORT).show();
this.finish()
finish() will complete current activity and backs to the previous activity.

MediaRecorder-recording video using mediarecorder

iam using mediarecorder to record video in android application. I will start and stop recording video multiple times i will start recording on Action_down and stop on Action_up this is going on well and iam able to store and play video file in mobile .
my problem is that since i have to start and stop recording video multiple times i can't use single output file becuase everytime it will get over written so everytime iam passing new file name and iam appending that to one outputfile everytime.iam getting every individual file and final outputfile in mobile but final file is having only what i have recorded for the first time because from second tab if see the file.mp4.length()is zero why it is ? anyone please try to help me. my code is as follows
package com.example.longtouch;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import android.hardware.Camera;
import android.hardware.Camera.CameraInfo;
import android.media.CamcorderProfile;
import android.media.MediaRecorder;
import android.net.rtp.AudioGroup;
import android.net.rtp.AudioStream;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.Handler.Callback;
import android.provider.MediaStore.Audio;
import android.provider.MediaStore.Files;
import android.provider.MediaStore.Video;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;
import android.view.View.OnTouchListener;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.Toast;
import android.support.v4.app.NavUtils;
public class MainActivity extends Activity implements OnTouchListener{
int i=1;
File outputFile;
File f1;
File f2;
MediaRecorder mediaRecorder;
ThreadProgress mThreadProgress;
ThreadProgress2 mThreadProgress2;
public int eventAction;
Handler handler;
Handler mHandler;
Button myButton;
FrameLayout myCameraPreview;
Button submit;
Button submit1;
LinearLayout ll;
ProgressBar progressBar;
int progressStatus=0;
MyCameraSurfaceView myCameraSurfaceView;
Camera myCamera;
boolean recording;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
recording=false;
myButton=(Button)findViewById(R.id.button_capture);
submit=(Button)findViewById(R.id.submit);
submit1=(Button)findViewById(R.id.submit1);
progressBar=(ProgressBar)findViewById(R.id.progress_bar);
progressBar.setMax(10000);
myCamera = getCameraInstance();
if(myCamera == null){
Toast.makeText(MainActivity.this,
"Fail to get Camera",
Toast.LENGTH_LONG).show();
}
// else
// myCamera.unlock();
myCameraSurfaceView = new MyCameraSurfaceView(this, myCamera);
myCameraPreview=(FrameLayout)findViewById(R.id.camera_preview);
myCameraPreview.addView(myCameraSurfaceView);
ll=(LinearLayout)findViewById(R.id.ll);
myCameraPreview.setOnTouchListener(this);
outputFile=new File("/sdcard/myvideo.mp4");
if(outputFile.exists()){
outputFile.delete();
outputFile=new File("/sdcard/myvideo.mp4");
try {
outputFile.createNewFile();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
else{
try {
outputFile.createNewFile();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
f1=new File("/sdcard/myvideo1.mp4");
if(f1.exists()){
f1.delete();
f1=new File("/sdcard/myvideo1.mp4");
try{
f1.createNewFile();
}
catch(Exception e){
e.printStackTrace();
}
}
else{
try{
f1.createNewFile();
}
catch(Exception e){
e.printStackTrace();
}
}
f2=new File("/sdcard/myvideo2.mp4");
if(f2.exists()){
f2.delete();
f2=new File("/sdcard/myvideo2.mp4");
try{
f2.createNewFile();
}
catch(Exception e){
e.printStackTrace();
}
}
else{
try{
f2.createNewFile();
}
catch(Exception e){
e.printStackTrace();
}
}
}
/* public int getFrontCameraId() {
CameraInfo ci = new CameraInfo();
for (int i = 0 ; i < Camera.getNumberOfCameras(); i++) {
Camera.getCameraInfo(i, ci);
if (ci.facing == CameraInfo.CAMERA_FACING_FRONT) return i;
}
return -1; // No front-facing camera found
}*/
private Camera getCameraInstance(){
// TODO Auto-generated method stub
Camera c = null;
try {
/* int index = getFrontCameraId();
if (index != -1)
c = Camera.open(index);*/
c = Camera.open(); // attempt to get a Camera instance
}
catch (Exception e){
// Camera is not available (in use or does not exist)
}
return c; // returns null if camera is unavailable
}
public void submit(View v){
// stop recording and release camera
// mediaRecorder.stop(); // stop the recording
// releaseMediaRecorder(); // release the MediaRecorder object
Log.d("outputFile",""+f1.length());
progressStatus=progressBar.getProgress();
//Exit after saved
// finish();
myButton.setText("capture");
recording=false;
submit.setVisibility(View.GONE);
}
public void submit1(View v){
// stop recording and release camera
// mediaRecorder.stop(); // stop the recording
// releaseMediaRecorder(); // release the MediaRecorder object
progressBar.setProgress(0);
progressStatus=0;
//Exit after saved
// finish();
myButton.setText("capture");
recording=false;
submit1.setVisibility(View.GONE);
}
public void display(View v){
Intent i=new Intent(this,VideoPlayer.class);
startActivity(i);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
public boolean onTouch(View arg0, final MotionEvent event) {
// TODO Auto-generated method stub
eventAction=event.getAction();
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
{
i=i+1;
Toast.makeText(getApplicationContext(),"action_down",Toast.LENGTH_SHORT).show();
//releaseCamera();
if(!prepareMediaRecorder()){
Toast.makeText(MainActivity.this,
"Fail in prepareMediaRecorder()!\n - Ended -",Toast.LENGTH_LONG).show();
finish();
}
progressBar.setProgress(progressStatus);
myButton.setText("STOP");
try{
mediaRecorder.start();
}
catch(Exception e){
e.printStackTrace();
Log.d("vd","exception at start method");
}
if(f1.exists()){
long l=f1.length();
Log.d("start","started"+l);
}
if(f2.exists()){
long m=f2.length();
Log.d("start","started"+m);
}
recording = true;
if(progressBar.getProgress()>=5000){
mThreadProgress2=new ThreadProgress2();
mThreadProgress2.start();
}
mHandler = new Handler(new Callback() {
public boolean handleMessage(final Message msg) {
runOnUiThread(new Runnable() {
public void run() {
if( event.getAction()!=MotionEvent.ACTION_UP){
progressBar.setProgress(msg.arg1);
}
if(progressBar.getProgress()==10000){
Log.d("unicorn","1000");
submit1.setVisibility(View.VISIBLE);
}
}
});
return false;
}
});
mThreadProgress=new ThreadProgress();
mThreadProgress.start();
handler = new Handler(new Callback() {
public boolean handleMessage(final Message msg) {
runOnUiThread(new Runnable() {
public void run() {
if( event.getAction()!=MotionEvent.ACTION_UP)
progressBar.setProgress(msg.arg1);
if(progressBar.getProgress()==5000){
submit.setVisibility(View.VISIBLE);
}
}
});
return false;
}
});
return true;
}
case MotionEvent.ACTION_UP:
{ // nothing to do
Toast.makeText(getApplicationContext(),"action_up",Toast.LENGTH_SHORT).show();
myButton.setText("capture");
mediaRecorder.stop(); // stop the recording
releaseMediaRecorder(); // release the MediaRecorder object
try {
myCamera.reconnect();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
//Exit after saved
// finish();
recording=false;
progressStatus=progressBar.getProgress();
if(i%2==0){
long len=f1.length();
Log.d("length",""+f1.getPath()+len);
Combine1 c1=new Combine1();
c1.start();
}
else{
long len=f2.length();
Log.d("length",""+f2.getPath()+len);
Combine2 c2=new Combine2();
c2.start();
}
break;
}
default:
return false;
}
return true;
}
private boolean prepareMediaRecorder(){
// myCamera = getCameraInstance();
mediaRecorder = new MediaRecorder();
myCamera.stopPreview();
myCamera.unlock();
mediaRecorder.setCamera(myCamera);
mediaRecorder.setAudioSource(MediaRecorder.AudioSource.CAMCORDER);
mediaRecorder.setVideoSource(MediaRecorder.VideoSource.CAMERA);
mediaRecorder.setProfile(CamcorderProfile.get(CamcorderProfile.QUALITY_HIGH));
// mediaRecorder.setVideoSize(400,400);
if(i%2==0){
Log.d("outputfile",""+f1.getPath()+f1.length());
mediaRecorder.setOutputFile(f1.getPath());
Log.d("outputfile",""+f1.getPath()+f1.length());
}
else{
Log.d("outputfile",""+f2.getPath()+f2.length());
mediaRecorder.setOutputFile(f2.getPath());
Log.d("outputfile",""+f2.getPath()+f2.length());
}
mediaRecorder.setMaxDuration(10000); // Set max duration 10 sec.
mediaRecorder.setMaxFileSize(5000000); // Set max file size 5M
// mediaRecorder.setOnInfoListener(this);
mediaRecorder.setPreviewDisplay(myCameraSurfaceView.getHolder().getSurface());
try {
mediaRecorder.prepare();
} catch (IllegalStateException e) {
Log.d("prepare","illegalstateexception");
e.printStackTrace();
releaseMediaRecorder();
Toast.makeText(getApplicationContext(),"illegal state exception",Toast.LENGTH_SHORT).show();
return false;
} catch (IOException e) {
Log.d("prepare","ioexception");
e.printStackTrace();
releaseMediaRecorder();
Toast.makeText(getApplicationContext(),"IOexception",Toast.LENGTH_SHORT).show();
return false;
}
Log.d("after prepare","after prepare f1"+f1.length());
Log.d("after prepare","after prepare f2"+f2.length());
return true;
}
public void combine(String file){
Log.d("combine","combining"+file);
try{
File inputFile=new File(file);
FileInputStream fis=new FileInputStream(inputFile);
long inputlen=inputFile.length();
Log.d("combine","lengthbefore write"+inputlen);
File outputFile = new File("/sdcard/myvideo.mp4");
FileOutputStream fos = new FileOutputStream(outputFile,true);
byte fileContent[]= new byte[(int)inputFile.length()];
fis.read(fileContent);
long len=outputFile.length();
Log.d("combine","lenth"+len);
fos.write(fileContent);
fis.close();
fos.close();
inputlen=inputFile.length();
len=outputFile.length();
Log.d("combine","inputlength"+inputlen);
Log.d("combine","lenth"+len);
/* File f= new File(file);
boolean deleted = f.delete();
if(deleted){
Log.d("combine","deleted"+file);
} */
}
catch(Exception e){
e.printStackTrace();
}
}
#Override
protected void onPause() {
super.onPause();
releaseMediaRecorder(); // if you are using MediaRecorder, release it first
releaseCamera(); // release the camera immediately on pause event
}
private void releaseMediaRecorder(){
if (mediaRecorder != null) {
mediaRecorder.reset(); // clear recorder configuration
mediaRecorder.release(); // release the recorder object
mediaRecorder = null;
// myCamera.lock(); // lock camera for later use
}
}
private void releaseCamera(){
if (myCamera != null){
myCamera.release(); // release the camera for other applications
myCamera = null;
}
}
public class MyCameraSurfaceView extends SurfaceView implements SurfaceHolder.Callback{
private SurfaceHolder mHolder;
private Camera mCamera;
public MyCameraSurfaceView(Context context, Camera camera) {
super(context);
mCamera = camera;
// Install a SurfaceHolder.Callback so we get notified when the
// underlying surface is created and destroyed.
mHolder = getHolder();
mHolder.addCallback(this);
// deprecated setting, but required on Android versions prior to 3.0
mHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
}
public void surfaceChanged(SurfaceHolder holder, int format, int weight,
int height) {
// If your preview can change or rotate, take care of those events here.
// Make sure to stop the preview before resizing or reformatting it.
if (mHolder.getSurface() == null){
// preview surface does not exist
return;
}
// stop preview before making changes
try {
mCamera.stopPreview();
} catch (Exception e){
// ignore: tried to stop a non-existent preview
}
// make any resize, rotate or reformatting changes here
// start preview with new settings
try {
mCamera.setPreviewDisplay(mHolder);
mCamera.startPreview();
} catch (Exception e){
}
}
public void surfaceCreated(SurfaceHolder holder) {
// TODO Auto-generated method stub
// The Surface has been created, now tell the camera where to draw the preview.
try {
mCamera.setPreviewDisplay(holder);
mCamera.startPreview();
} catch (IOException e) {
}
}
public void surfaceDestroyed(SurfaceHolder holder) {
// TODO Auto-generated method stub
}
}
public class ThreadProgress extends Thread implements Runnable {
int progressValue=progressStatus;
public void run() {
while( progressBar.getProgress()<5000 && eventAction!=MotionEvent.ACTION_UP ) {
Log.d("unicorn","in while loop"+progressValue);
progressValue++;
Message message = new Message();
message.arg1 = progressValue;
if(progressValue<=5000 && eventAction!=MotionEvent.ACTION_UP)
handler.sendMessage(message);
}
}
}
public class ThreadProgress2 extends Thread implements Runnable {
int progressValue=progressStatus;
#Override
public void run() {
while( progressBar.getProgress()<10000 && eventAction!=MotionEvent.ACTION_UP ) {
// try{
Log.d("unicorn2","in while loop"+progressValue);
progressValue++;
Message message = new Message();
message.arg1 = progressValue;
if(progressValue<=10000 && eventAction!=MotionEvent.ACTION_UP)
mHandler.sendMessage(message);
//Thread.sleep(1000);
//} catch (InterruptedException e){
// e.printStackTrace();
// break;
// }
}
}
}
public class Combine1 extends Thread implements Runnable{
public void run(){
try{
int c;
FileInputStream fin=new FileInputStream(f1);
FileOutputStream fout=new FileOutputStream(outputFile,true);
long len1=f1.length();
Log.d("length","myvideo1.mp4"+len1);
long len2=outputFile.length();
Log.d("length","myvideo.mp4"+len2);
while((c=fin.read())!=-1){
fout.write(c);
}
len2=outputFile.length();
Log.d("length","myvideo.mp4"+len2);
fin.close();
fout.flush();
fout.close();
}
catch(Exception e){
e.printStackTrace();
}
}
}
public class Combine2 extends Thread implements Runnable{
public void run(){
try{
int j=0;
FileInputStream fin=new FileInputStream(f2);
FileOutputStream fout=new FileOutputStream(outputFile,true);
long len1=f2.length();
Log.d("length","myvideo2.mp4"+len1);
long len2=outputFile.length();
Log.d("length","myvideo.mp4"+len2);
while((j=fin.read())!=-1){
fout.write(j);
}
len2=outputFile.length();
Log.d("length","myvideo.mp4"+len2);
fin.close();
fout.flush();
fout.close();
}
catch(Exception e){
e.printStackTrace();
}
}
}
}
In order to combine multiple video files you should use mp4parser library : https://mp4parser.googlecode.com/svn/trunk/examples/src/main/java/com/googlecode/mp4parser/AppendExample.java

data/data/com.package/databases folder isn't showed

I made an android dictionary application. I have created a database named "kamusJawa.sqlite" and copied it to the assets folder. I tried the code in this link Own Database in Assets Folder on Android Eclipse Project
This is my database manager class:
package com.kamusJI;
public class DBHelper extends SQLiteOpenHelper{
private static String DBPATH = "/data/data/com.kamusJI/databases/";
private static String DBNAME = "kamusJawa.sqlite";
private SQLiteDatabase DBSQ;
private final Context KJICtx;
public DBHelper(Context context) throws IOException {
super(context, DBNAME, null, 1);
this.KJICtx = context;
// TODO Auto-generated constructor stub
boolean dbexist = cekDB();
if (dbexist) {
//System.out.println("Database exists");
openDB();
} else {
System.out.println("Database doesn't exist");
createDB();
}
}
public void createDB() throws IOException{
boolean dbExist = cekDB();
if(!dbExist){
this.getReadableDatabase();
try{
salinDB();
}catch (IOException e){
throw new Error("Gagal menyalin database");
}
}
}
boolean cekDB() {
//SQLiteDatabase cekDatabase = null;
boolean cekdb = false;
try{
String path = DBPATH + DBNAME;
File dbfile = new File(path);
//cekDatabase = SQLiteDatabase.openDatabase(path, null, SQLiteDatabase.OPEN_READONLY);
cekdb = dbfile.exists();
}catch(SQLException e){
System.out.println("Database tidak ada");
}
return cekdb;
//return cekDatabase !=null ? true : false;
}
private void salinDB() throws IOException{
AssetManager AM = KJICtx.getAssets();
File DbFile = new File(DBPATH+DBNAME);
InputStream in = KJICtx.getAssets().open(DBNAME);
//OutputStream out = new FileOutputStream(DbFile);
OutputStream out = new FileOutputStream("/data/data/com.kamusJI/databases/kamusJawa.sqlite");
DbFile.createNewFile();
byte[] b = new byte[1024];
int i, r;
String[] Files = AM.list("");
Arrays.sort(Files);
i= 1;
String fdb = String.format("kamusJawa.db.00%d", i);
while(Arrays.binarySearch(Files, fdb)>=0){
//InputStream in = AM.open(fdb);
while(( r = in.read(b))>0)
out.write(b,0,r);
in.close();
i++;
fdb = String.format("kamusJawa.db.00%d", i);
}
out.flush();
out.close();
}
public void openDB() throws SQLException{
String path = DBPATH+DBNAME;
DBSQ = SQLiteDatabase.openDatabase(path, null, SQLiteDatabase.OPEN_READONLY);
}
public synchronized void close(){
if(DBSQ !=null)
DBSQ.close();
super.close();
}
#Override
public void onCreate(SQLiteDatabase arg0) {
// TODO Auto-generated method stub
}
#Override
public void onUpgrade(SQLiteDatabase arg0, int arg1, int arg2) {
// TODO Auto-generated method stub
}
}
and this is my main class:
package com.kamusJI;
public class KJI extends ListActivity {
private KJI this_class = this;
String[] Menu = {"Basa Jawa", "Bahasa Indonesia", "Tambah Data"};
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
setListAdapter(new ArrayAdapter<String>(this, R.layout.row, R.id.Cari, Menu));
ListView lv = getListView();
lv.setTextFilterEnabled(false);
/* Defines On Item Click callback method */
lv.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position,
long id) {
Intent action = null;
switch(position) {
case 0:
case 1:
action = new Intent(getApplicationContext(), Cari.class);
action.putExtra("MODE", position);
break;
case 2:
action = new Intent(getApplicationContext(), Tambah.class);
action.putExtra("MODE", position);
break;
case 3:
finish();
return;
}
startActivity(action);
Toast.makeText(getApplicationContext(), ((TextView) view).getText(), Toast.LENGTH_SHORT).show();
}
});
}
public void InitDatabase() {
AsyncTask<String, Void, String> InitDB = new AsyncTask<String, Void, String>() {
Dialog progress = null;
String msg;
DBHelper dbhelper;
#Override
protected void onPreExecute() {
try {
dbhelper = new DBHelper(this_class);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
if (!dbhelper.cekDB())
progress = ProgressDialog.show(this_class, "", "Installing Database.\nPlease wait.");
super.onPreExecute();
}
#Override
protected String doInBackground(String... params) {
try {
dbhelper.createDB();
msg = "Database successfully installed.";
} catch (IOException ioe) {
msg = "Database installation failed.";
}
return msg;
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
if (progress!=null) {
progress.dismiss();
Toast.makeText(getApplicationContext(), result, Toast.LENGTH_SHORT).show();
}
}
};
InitDB.execute(new String());
}
}
When I run my application, then I go to file explorer, I can't find the data/data/com.kamusJI/databases. How it can be like that?
change your database name extension to .db
You need special permissions like root access to read the path:
/data/data/com.package/databases

Resources