Why am I getting a null pointer exception? - android-emulator

The title of this problem describes my problem. I have tried fixing this for a while and i am tired of searching and would like some help please. It used to work until I added the Handler and runner. I am trying to make an application that is a simple clock application that the user can set to any time that they want to. Whenever I go to run the application, it opens and then says it would not start properly. This is an activity that is set by another activity and then it changes the values it receives, it also displays these values in textviews.
package CoopFun.Clocks;
import android.os.Bundle;
import android.os.Handler;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.widget.TextView;
import android.content.Intent;
import android.app.Activity;
public class ClockMain extends Activity {
int Hours;
int Minutes;
int Seconds;
String TimeOfDayS;
TextView HoursMainV;
TextView MinutesMainV;
TextView SecondsMainV;
TextView TimeOfDayMainV;
Timer oneSecond;
public void onCreate(Bundle bundle) {
super.onCreate(bundle);
setContentView(R.layout.clock_main);
requestWindowFeature(Window.FEATURE_NO_TITLE);
Bundle extras = getIntent().getExtras();
if (extras == null) {
return;
}
int Hour = extras.getInt("HoursS");
Hour = Hours;
int Minute = extras.getInt("MinutesS");
Minute = Minutes;
int Second = extras.getInt("SecondsS");
Second = Seconds;
String TimeOfDaySs = extras.getString("TimeOfDayS");
TimeOfDaySs = TimeOfDayS;
HoursMainV = (TextView) findViewById(R.id.HoursMainV);
HoursMainV.setText(""+Hour);
MinutesMainV = (TextView) findViewById(R.id.MinutesMainV);
MinutesMainV.setText(":"+Minute);
SecondsMainV = (TextView) findViewById(R.id.SecondsMainV);
SecondsMainV.setText(":"+Second);
TimeOfDayMainV = (TextView) findViewById(R.id.TimeOfDayMainV);
TimeOfDayMainV.setText(" "+TimeOfDaySs);
final Handler handler=new Handler();
final Runnable r = new Runnable()
{
public void run()
{
++Seconds;
if(Seconds == 60){
++Minutes;
Seconds = 0;
if(Minutes == 60) {
++Hours;
Minutes = 0;
if(Hours == 12){
if(TimeOfDayS.equals("AM")) {
TimeOfDayS = "PM";
} else{
TimeOfDayS = "AM";
}
Hours = 0;
}
}
}
HoursMainV.append(""+Hours);
if(Minutes <=9) {
MinutesMainV.append(":0"+Minutes);
} else {
MinutesMainV.append(":"+Minutes);
}
if(Seconds <=9) {
SecondsMainV.append(":0"+Seconds);
} else {
SecondsMainV.append(":"+Seconds);
}
TimeOfDayMainV.append(" " + TimeOfDayS);
handler.postDelayed(this, 1000);
}
};
handler.postDelayed(r, 1000);
}
}
XML:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="horizontal">
<TextView
android:textSize="50dip"
android:id="#+id/HoursMainV"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="25dip"></TextView>
<TextView
android:textSize="50dip"
android:id="#+id/MinutesMainV"
android:layout_width="wrap_content"
android:layout_height="wrap_content"></TextView>
<TextView
android:textSize="50dip"
android:id="#+id/SecondsMainV"
android:layout_width="wrap_content"
android:layout_height="wrap_content"></TextView>
<TextView
android:textSize="50dip"
android:id="#+id/TimeOfDayMainV"
android:layout_width="wrap_content"
android:layout_height="wrap_content"></TextView>
</LinearLayout>
Manifest:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="CoopFun.Clocks"
android:versionCode="1"
android:versionName="1.0">
<application android:icon="#drawable/icon" android:label="#string/app_name">
<activity android:name=".Clock"
android:label="#string/app_name">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity android:name=".ClockMain">
</activity>
</application>
</manifest>
Thank you.

int Hour = extras.getInt("HoursS");
Hour = Hours;
int Minute = extras.getInt("MinutesS");
Minute = Minutes;
int Second = extras.getInt("SecondsS");
Second = Seconds;
String TimeOfDaySs = extras.getString("TimeOfDayS");
TimeOfDaySs = TimeOfDayS;
Change above code with this::
int Hour = extras.getInt("HoursS");
Hours = Hour;
int Minute = extras.getInt("MinutesS");
Minutes = Minute;
int Second = extras.getInt("SecondsS");
Seconds = Second;
String TimeOfDaySs = extras.getString("TimeOfDayS");
TimeOfDayS = TimeOfDaySs;
Simply, u were getting null pointer exception bcoz u were setting null values to Hour,Minute,Second and TimeOfDaySs and accessing them.
Cheers....!!!

Related

Android widget background color not updating

I want to change the widget background transparency dynamically. The user can define a custom value in percent in my SettingsActivity. After I call updateWidget() from my activity the widget does not update immediately. It is only working if I re-add the widget.
When I set a breaking I see that updateWidgetListView() is called.
widget_layout_black.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/widget_layout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<LinearLayout
android:layout_width="match_parent"
android:background="#drawable/primary_rounded_background_black"
android:layout_height="wrap_content">
<TextView
android:id="#+id/newTaskButton"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:clickable="false"
android:layout_gravity="center_vertical"
android:textIsSelectable="false"
android:fontFamily="sans-serif-light"
android:layout_marginBottom="2dp"
android:paddingTop="5dp"
android:paddingRight="10dp"
android:paddingLeft="10dp"
android:text="#string/tasks"
android:background="#color/black"
android:gravity="center_vertical"
android:textColor="#color/white"
android:textAppearance="?android:attr/textAppearanceMedium"
android:drawableRight="#drawable/add" />
</LinearLayout>
<ListView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/widgetScheduledTasksListView"
android:layout_marginRight="16dp"
android:layout_marginLeft="16dp"
android:layout_marginBottom="16dp"
android:dividerHeight="0dp"
android:divider="#null"
android:layout_centerHorizontal="true" />
<TextView
android:id="#+id/empty_view"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center"
android:text="#string/noScheduledTasks"
android:textAppearance="?android:attr/textAppearanceMedium"
android:textColor="#000000"
android:visibility="gone" />
SettingsActivity.java
public void updateWidget() {
Intent intent = new Intent(this, WidgetProvider.class);
intent.setAction(AppWidgetManager.ACTION_APPWIDGET_UPDATE);
int[] ids = {R.xml.widgetinfo};
intent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_IDS, ids);
sendBroadcast(intent);
}
WidgetProvider.java
#Override
public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds) {
final int numberOfWidgets = appWidgetIds.length;
for (int i = 0; i < numberOfWidgets; ++i) {
RemoteViews remoteViews = updateWidgetListView(context,appWidgetIds[i]);
remoteViews.setOnClickPendingIntent(R.id.newTaskButton, getPendingSelfIntent(context, ACTION_NEW));
appWidgetManager.updateAppWidget(appWidgetIds[i], remoteViews);
}
super.onUpdate(context, appWidgetManager, appWidgetIds);
}
private RemoteViews updateWidgetListView(Context context, int appWidgetId) {
RemoteViews remoteViews = new RemoteViews(context.getPackageName(), R.layout.widget_layout_black);
Intent svcIntent = new Intent(context, WidgetService.class);
svcIntent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, appWidgetId);
svcIntent.setData(Uri.parse(svcIntent.toUri(Intent.URI_INTENT_SCHEME)));
remoteViews.setRemoteAdapter(appWidgetId, R.id.widgetScheduledTasksListView, svcIntent);
remoteViews.setEmptyView(R.id.widgetScheduledTasksListView, R.id.empty_view);
final Intent onClickIntent = new Intent(context, WidgetProvider.class);
onClickIntent.setAction(WidgetProvider.ACTION_OPEN);
onClickIntent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, appWidgetId);
onClickIntent.setData(Uri.parse(onClickIntent.toUri(Intent.URI_INTENT_SCHEME)));
final PendingIntent onClickPendingIntent = PendingIntent.getBroadcast(context, 0, onClickIntent, PendingIntent.FLAG_UPDATE_CURRENT);
remoteViews.setPendingIntentTemplate(R.id.widgetScheduledTasksListView, onClickPendingIntent);
remoteViews.setInt(R.id.widget_layout, "setBackgroundColor", getBackgroundWithTransparencyColor(context)); // Set background color
return remoteViews;
}
public int getBackgroundWithTransparencyColor(Context context) {
int white = context.getResources().getColor(R.color.white);
int transparencyInPercent = preferences.getInt(context.getResources().getString(R.string.keyWidgetBackgroundTransparency), 25);
try {
double value = 255.0 / 100 * (100 - transparencyInPercent);
return ColorUtils.setAlphaComponent(white, (int) value);
} catch (Exception e) {
e.printStackTrace();
return white;
}
}

How do I use the service on Android Top 5

I've used a service in my program but the top 5 Android phone goes to sleep as soon as the service does nothing.
It works on Android 4 without any problems.
pls help me.
in Activity
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
startService(new Intent(this , MyService.class));
}
}
in Service
public class MyService extends android.app.Service {
private PowerManager pm;
private WifiManager wm;
#Nullable
#Override
public IBinder onBind(Intent intent) {
return null;
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
//do something code
return START_STICKY;
}
#Override
public void onTaskRemoved(Intent rootIntent) {
if (android.os.Build.VERSION.SDK_INT >= 21) {
pm = (PowerManager) getApplicationContext().getSystemService(Context.POWER_SERVICE);
final PowerManager.WakeLock wakeLock = pm.newWakeLock((PowerManager.PARTIAL_WAKE_LOCK), "TAG");
wakeLock.acquire();
wm = (WifiManager) getApplicationContext().getSystemService(Context.WIFI_SERVICE);
WifiManager.WifiLock lock = wm.createWifiLock(WifiManager.WIFI_MODE_FULL, "LockTag");
lock.acquire();
Intent restartServiceIntent = new Intent(getApplicationContext(),
MyService.class);
restartServiceIntent.setPackage(getPackageName());
PendingIntent restartServicePendingIntent = PendingIntent.getService(
getApplicationContext(), 0, restartServiceIntent,
PendingIntent.FLAG_ONE_SHOT);
AlarmManager alarmService = (AlarmManager) getApplicationContext()
.getSystemService(Context.ALARM_SERVICE);
long thirtySecondsFromNow = 1000;
alarmService.set(AlarmManager.RTC_WAKEUP, thirtySecondsFromNow, restartServicePendingIntent);
ComponentName receiver = new ComponentName(getApplicationContext(), MyService.class);
PackageManager pm = getApplicationContext().getPackageManager();
pm.setComponentEnabledSetting(receiver,
PackageManager.COMPONENT_ENABLED_STATE_DISABLED,
PackageManager.DONT_KILL_APP);
super.onTaskRemoved(rootIntent);
}
}
}
in Manifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="app.service">
<uses-permission android:name="android.permission.WAKE_LOCK" />
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:roundIcon="#mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="#style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<service
android:name=".MyService"
android:enabled="true"
android:exported="false"
android:label="my"
android:largeHeap="true"
android:stopWithTask="false" />
</application>

.setPreviewFpsRange(): Having problems updating frames per second in camera .setParameters()

UPDATED 28 October 2015 to reflect current progress.
I have an application that allows the user to set camera parameters for Motion JPEG recording, create an MJPEG file, and then the user can modify those settings and create another file with the updated settings. I am having a problem updating the frames per second setting when the initial value is something other than 30 FPS. When the initial value is 30 FPS, I can update to a different FPS level and sucessfully record a video AT THAT LEVEL. However, I cannot update from a level that is not equal to 30FPS to another FPM level. I get a crash with LogCat showing a problem at
camera.setParameters(parameters);
Full LogCat of error is below,
10-26 20:27:36.414: E/AndroidRuntime(2275): FATAL EXCEPTION: main
10-26 20:27:36.414: E/AndroidRuntime(2275): java.lang.RuntimeException: setParameters failed
10-26 20:27:36.414: E/AndroidRuntime(2275): at android.hardware.Camera.native_setParameters(Native Method)
10-26 20:27:36.414: E/AndroidRuntime(2275): at android.hardware.Camera.setParameters(Camera.java:1333)
10-26 20:27:36.414: E/AndroidRuntime(2275): at net.blepsias.riverwatch.RiverWatch.setCamera(RiverWatch.java:191)
10-26 20:27:36.414: E/AndroidRuntime(2275): at net.blepsias.riverwatch.RiverWatch.onClick(RiverWatch.java:167)
10-26 20:27:36.414: E/AndroidRuntime(2275): at android.view.View.performClick(View.java:3514)
10-26 20:27:36.414: E/AndroidRuntime(2275): at android.view.View$PerformClick.run(View.java:14111)
10-26 20:27:36.414: E/AndroidRuntime(2275): at android.os.Handler.handleCallback(Handler.java:605)
10-26 20:27:36.414: E/AndroidRuntime(2275): at android.os.Handler.dispatchMessage(Handler.java:92)
10-26 20:27:36.414: E/AndroidRuntime(2275): at android.os.Looper.loop(Looper.java:137)
10-26 20:27:36.414: E/AndroidRuntime(2275): at android.app.ActivityThread.main(ActivityThread.java:4429)
10-26 20:27:36.414: E/AndroidRuntime(2275): at java.lang.reflect.Method.invokeNative(Native Method)
10-26 20:27:36.414: E/AndroidRuntime(2275): at java.lang.reflect.Method.invoke(Method.java:511)
10-26 20:27:36.414: E/AndroidRuntime(2275): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:784)
10-26 20:27:36.414: E/AndroidRuntime(2275): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:551)
10-26 20:27:36.414: E/AndroidRuntime(2275): at dalvik.system.NativeStart.main(Native Method)
Checking the LogCat cited line 5 and 6, these correspond to:
(191) camera.setParameters(parameters);
(167) setCamera(camera);
Below is the application. I'll also include the layout .xml file for reference, as well as a screenshot for grounding.
RiverWatch.java
public class RiverWatch extends Activity implements OnClickListener, SurfaceHolder.Callback, Camera.PreviewCallback {
public static final String LOGTAG = "VIDEOCAPTURE";
String szBoundaryStart = "\r\n\r\n--myboundary\r\nContent-Type: image/jpeg\r\nContent-Length: ";
String szBoundaryDeltaTime = "\r\nDelta-time: 110";
String szBoundaryEnd = "\r\n\r\n";
private SurfaceHolder holder;
private Camera camera;
private CamcorderProfile camcorderProfile;
Spinner spinnerCamcorderProfile;
public TextView tvFramesPerSecond, tvJpegQuality, tvSegmentDuration;
boolean bRecording = false;
boolean bPreviewRunning = false;
int intFramesPerSecond = 30000; //this is 30fps...mult by 1,000
int intJpegQuality=50; //must be above 20
int intSegmentDuration=10;
boolean ckbxRepeat=false;
byte[] previewCallbackBuffer;
File mjpegFile;
FileOutputStream fos;
BufferedOutputStream bos;
Button btnStartRecord, btnStopRecord, btnExit, btnChange;
Camera.Parameters parameters;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Date T = new Date();
SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
String szFileName = "videocapture-"+sdf.format(T)+"-";
try {
mjpegFile = File.createTempFile(szFileName, ".mjpeg", Environment.getExternalStorageDirectory());
} catch (Exception e) {
finish();
}
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
setContentView(R.layout.main);
tvFramesPerSecond = (TextView) this.findViewById(R.id.textboxframespersecondxml);
int iFPS = intFramesPerSecond/1000;
String szFPS = Integer.toString(iFPS);
tvFramesPerSecond.setClickable(true);
tvFramesPerSecond.setText(szFPS);
tvFramesPerSecond.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
getSupportedPreviewFpsRange();
}
});
tvJpegQuality = (TextView) this.findViewById(R.id.textboxJpegQualityxml);
String szJpegQuality = Integer.toString(intJpegQuality);
tvJpegQuality.setText(szJpegQuality);
tvSegmentDuration = (TextView) this.findViewById(R.id.textboxSegmentDurationxml);
String szSegmentDuration = Integer.toString(intSegmentDuration);
tvSegmentDuration.setText(szSegmentDuration);
btnStartRecord = (Button) this.findViewById(R.id.StartRecordButton);
btnStartRecord.setOnClickListener(this);
btnStopRecord = (Button) this.findViewById(R.id.StopRecordButton);
btnStopRecord.setOnClickListener(this);
btnExit = (Button) this.findViewById(R.id.ExitButton);
btnExit.setOnClickListener(this);
btnChange = (Button) this.findViewById(R.id.ChangeButton);
btnChange.setOnClickListener(this);
camcorderProfile = CamcorderProfile.get(CamcorderProfile.QUALITY_TIME_LAPSE_480P);
SurfaceView cameraView = (SurfaceView) findViewById(R.id.CameraView);
holder = cameraView.getHolder();
holder.addCallback(this);
holder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
cameraView.setClickable(true);
cameraView.setOnClickListener(this);
}
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.StartRecordButton:
try {
fos = new FileOutputStream(mjpegFile);
bos = new BufferedOutputStream(fos);
bRecording = true;
} catch (FileNotFoundException e) {
e.printStackTrace();
}
Toast.makeText(this, "Recording started.", Toast.LENGTH_SHORT).show();
break;
case R.id.StopRecordButton:
try {
bos.flush();
bos.close();
} catch (IOException e) {
e.printStackTrace();
}
Toast.makeText(this, "Recording stopped.", Toast.LENGTH_SHORT).show();
break;
case R.id.ChangeButton:
//Frames Per Second- expressed x1000 in the function
String szFPS=tvFramesPerSecond.getText().toString();
int iFPS = Integer.parseInt(szFPS);
intFramesPerSecond = iFPS *1000;
//Jpeg quality- cant be <20 or >100, checks this and populates field with entered or corrected value.
String szJpegQuality=tvJpegQuality.getText().toString();
int intJpegQualityTemp = Integer.parseInt(szJpegQuality);
if (intJpegQualityTemp < 21){//...can't be less than 21
intJpegQuality = 21;
}else if(intJpegQualityTemp > 100){//can't be greater than 100
intJpegQuality = 100;
}else{ //quality is between 21 and 100...
intJpegQuality = intJpegQualityTemp;
}
szJpegQuality = Integer.toString(intJpegQuality);
tvJpegQuality.setText(szJpegQuality);
//Segment duration
String szSegmentDuration=tvSegmentDuration.getText().toString();
intSegmentDuration = Integer.parseInt(szSegmentDuration);
releaseCamera();
setCamera(camera);
camera.startPreview();
Toast.makeText(this, "Change button pressed.", Toast.LENGTH_SHORT).show();
break;
case R.id.ExitButton:
System.exit(0);
break;
}
}
public void releaseCamera(){
camera.stopPreview();
//camera.release(); //...cause crash
//camera = null;
}
public void setCamera(Camera camera){
Camera.Parameters parameters=camera.getParameters();
parameters.setPreviewFpsRange(intFramesPerSecond, intFramesPerSecond);//note: This is fps x 1000 (!)
parameters.setPreviewSize(camcorderProfile.videoFrameWidth, camcorderProfile.videoFrameHeight);
Log.v(LOGTAG,"FPS: " + parameters.getSupportedPreviewFpsRange());
camera.setParameters(parameters);
}
public void getSupportedPreviewFpsRange(){
/****************************************************************
* getSupportedPreviewFpsRange()- Returns specified frame rate
* (.getSupportedPreviewFpsRange()) to log file and also displays
* as toast message.
****************************************************************/
Camera.Parameters camParameter = camera.getParameters();
List<int[]> frame = camParameter.getSupportedPreviewFpsRange();
Iterator<int[]> supportedPreviewFpsIterator = frame.iterator();
while (supportedPreviewFpsIterator.hasNext()) {
int[] tmpRate = supportedPreviewFpsIterator.next();
StringBuffer sb = new StringBuffer();
sb.append("SupportedPreviewRate: ");
for (int i = tmpRate.length, j = 0; j < i; j++) {
sb.append(tmpRate[j] + ", ");
}
Log.d(LOGTAG, "FPS6: " + sb.toString());
Toast.makeText(this, "FPS = "+sb.toString(), Toast.LENGTH_SHORT).show();
}//*****************end getSupportedPreviewFpsRange()**********************
}
public void surfaceCreated(SurfaceHolder holder) {
camera = Camera.open();
}
#SuppressLint("NewApi")
public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
if (!bRecording) {
if (bPreviewRunning = true){
camera.stopPreview();
} try {
parameters = camera.getParameters();
parameters.setPreviewSize(camcorderProfile.videoFrameWidth, camcorderProfile.videoFrameHeight);
parameters.setPreviewFpsRange(intFramesPerSecond, intFramesPerSecond);//note: This is fps x 1000 (!)
//p.setPreviewFrameRate(intFramesPerSecond);
camera.setParameters(parameters);
camera.setPreviewDisplay(holder);
camera.setPreviewCallback(this);
camera.setDisplayOrientation(90);
camera.startPreview();
bPreviewRunning = true;
}
catch (IOException e) {
e.printStackTrace();
}
}
}
public void surfaceDestroyed(SurfaceHolder holder) {
if (bRecording) {
bRecording = false;
try {
bos.flush();
bos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
bPreviewRunning = false;
camera.release();
finish();
}
public void onPreviewFrame(byte[] b, Camera c) {
if (bRecording) {
// Assuming ImageFormat.NV21
if (parameters.getPreviewFormat() == ImageFormat.NV21) {
try {
YuvImage im = new YuvImage(b, ImageFormat.NV21, parameters.getPreviewSize().width, parameters.getPreviewSize().height, null);
Rect r = new Rect(0,0,parameters.getPreviewSize().width,parameters.getPreviewSize().height);
ByteArrayOutputStream jpegByteArrayOutputStream = new ByteArrayOutputStream();
im.compressToJpeg(r, intJpegQuality, jpegByteArrayOutputStream);//note: qual = 20 or less doesn't work.
byte[] jpegByteArray = jpegByteArrayOutputStream.toByteArray();
byte[] boundaryBytes = (szBoundaryStart + jpegByteArray.length + szBoundaryDeltaTime + szBoundaryEnd).getBytes();
bos.write(boundaryBytes);
bos.write(jpegByteArray);
bos.flush();
//bos.close();
} catch (IOException e) {
e.printStackTrace();
}
} else {
Log.v(LOGTAG,"NOT THE RIGHT FORMAT");
}
}
}
#Override
public void onConfigurationChanged(Configuration conf){
super.onConfigurationChanged(conf);
}
}
Layout main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<LinearLayout
android:orientation="horizontal"
android:layout_width="wrap_content"
android:layout_height="wrap_content">
<Button
android:id="#+id/StartRecordButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Start Recording" />
<Button
android:id="#+id/StopRecordButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Stop Recording" />
<Button
android:id="#+id/ChangeButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="50dip"
android:text="Reset settings" />
</LinearLayout>
<LinearLayout
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="right">
<TextView
style="#style/myStyle"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Frames/second:" />
<EditText
android:id="#+id/textboxframespersecondxml"
android:editable="true"
style="#style/myStyle"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:gravity="right"
android:text="0"
android:layout_marginRight="10dip"/>
</LinearLayout>
<LinearLayout
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="right">
<TextView
style="#style/myStyle"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="JPEG image quality:" />
<EditText
android:id="#+id/textboxJpegQualityxml"
android:editable="true"
style="#style/myStyle"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:gravity="right"
android:text="0"
android:layout_marginRight="10dip"/>
</LinearLayout>
<LinearLayout
android:orientation="horizontal"
android:layout_width="fill_parent"
android:layout_height="wrap_content">
<TextView
style="#style/myStyle"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="10dip"
android:text="Camcorder profile: " />
<LinearLayout
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="right">
<TextView
style="#style/myStyle"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Segment duration (file length):" />
<EditText
android:id="#+id/textboxSegmentDurationxml"
android:editable="true"
style="#style/myStyle"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:gravity="right"
android:text="0"
android:layout_marginRight="10dip"/>
<TextView
style="#style/myStyle"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text=" minutes" />
</LinearLayout>
<LinearLayout
android:orientation="horizontal"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:gravity="right" >
<CheckBox
android:id="#+id/repeat"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Repeat" />
<Button
android:id="#+id/ExitButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Exit Application" />
</LinearLayout>
<SurfaceView
android:id="#+id/CameraView"
android:layout_width="fill_parent"
android:layout_height="fill_parent" />
</LinearLayout>
Screenshot: Showing fields, buttons, and surface config
Resolution: It appears that much of the above erratic behaviour may be related to the primary testing device which is a Panasonic Toughpad JT-B1. Running
.getSupportedPreviewFpsRange();
on this device returns a range of 8,000-30,000 fps. However, many values in this range result in crashes, and some values outside of this range appear to work fine. Testing a Samsung S4 Active resulted in none of these inconsistencies, with all of the values in the returned range (4,000 - 30,000) working fine, and no tested values outside of this range demonstrating any functionality as expected.
Camera API does not allow to set the preview FPS range to arbitrary values. You are supposed to query the camera parameters for the list of supported ranges, and any other combination is not guaranteed to work.
In principle, using unsupported values for Camera.setParameters() is undefined behavior. Different devices will fail or work differently when you try the same inputs.
Definitely, though, you should stop preview to change camera parameters, and restart the preview after that.
Other than that, you probably can use a workaround to hold on to supported parameters. To achieve 2 fps, and switch to 10 fps, you don't need to change camera settings. Your logic can filter out relevant frames in your onPreviewFrame() by timestamp.
Furthermore, your code is suboptimal when it comes to preview callbacks. First of all, you should open the camera on a separate handler thread, then the preview callbacks will not arrive on the UI thread (the newer versions of Android become even more jealous about apps hijacking the Main thread for CPU or network intensive tasks).
Second, consider using camera.setPreviewCallbackWithBuffer() to avoid unnecessary garbage collection. An extra advantage of this technique is that if you only prepare one preview buffer, you will only receive preview callbacks when you release it. So, you can simply use the code:
public void onPreviewFrame(byte[] data, Camera camera) {
long timestampBeforecompression = SystemClock.uptimeMillis();
compress(data);
long compressionMillis = SystemClock.uptimeMillis() - timestampBeforecompression;
SystemClock.sleep(1000000/intFramesPerSecond - compressionMillis);
camera.addCallbackBuffer(data);
}
Maybe, you can be more precise if you also compensate for the current camera frame rate, but this is probably not critical when speaking about 2 or 3 FPS.
Finally, there is another hint: many devices still support the deprecated setPreviewFrameRate(), and even declare the supported FPS values that may be of interest for you:
[1, 2, 3, 4, 5, 8, 10, 15, 20, 30]
on my no-name Snapdragon-801 tablet.

Android Fragment activity shown fullscreen

I have a question regarding a fragment layout of an OSM Map. I'd like to display the fragment within the activity in full screen modus.
However, the map is only shown on two thirds of the screen.
How can this be achieved?
Can this be done only be editing the .xml file or do I need to make any changes at the manifest or main activity as well?
Here the .xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="vertical" >
<fragment
android:id="#+id/map"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="8.01" >
</fragment>
</LinearLayout>
Here is the MapFragment.java file:
package com.example.uadclient;
import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Patter
import org.osmdroid.DefaultResourceProxyImpl;
import org.osmdroid.ResourceProxy;
import org.osmdroid.bonuspack.overlays.ExtendedOverlayItem;
import org.osmdroid.bonuspack.overlays.ItemizedOverlayWithBubble;
import org.osmdroid.bonuspack.overlays.Polyline;
import org.osmdroid.bonuspack.routing.Road;
import org.osmdroid.bonuspack.routing.RoadManager;
import org.osmdroid.bonuspack.routing.RoadNode;
import org.osmdroid.tileprovider.tilesource.TileSourceFactory;
import org.osmdroid.util.GeoPoint;
import org.osmdroid.views.MapController;
import org.osmdroid.views.MapView;
import org.osmdroid.views.overlay.ItemizedIconOverlay;
import org.osmdroid.views.overlay.Overlay;
import org.osmdroid.views.overlay.OverlayItem;
import org.osmdroid.views.overlay.PathOverlay;
import android.app.Fragment;
import android.content.res.TypedArray;
import android.graphics.Color;
import android.graphics.drawable.Drawable;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import android.widget.Toast;
import com.example.uadclient.R;
public class MapFragment extends Fragment {
private MapController mMapController;
private MapView mMapView;
private ItemizedIconOverlay<OverlayItem> myLocationOverlay;
protected ItemizedOverlayWithBubble<ExtendedOverlayItem> roadNodes;
protected PathOverlay roadOverlay;
FileInputStream fis = null;
private ResourceProxy mResourceProxy;
private LocationManager mLocMgr;
String s = "";
String s1 = "";
String s2 = "";
String lon = "";
String lat = "";
int mIncr = 10000;
int counter;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
mResourceProxy = new DefaultResourceProxyImpl(inflater.getContext().getApplicationContext());
mMapView = new MapView(inflater.getContext(), 256, mResourceProxy);
//read GPS data from file
readfromFile();
readfromFile2();
readfromFile();
String str1;
str1 = s1.toString();
readfromFile2();
String str2;
str2 = s2.toString();
try {
countLines();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
lon = str1;
lat = str2;
while (counter > 0){ //Anzahl Zeilen -> Anzahl der Punkte
double var_lon = Double.parseDouble(lon);
double var_lat = Double.parseDouble(lat);
View v = inflater.inflate(R.layout.meetfragment, null);
mMapView = (MapView) v.findViewById(R.id.mapview);
mMapView.setTileSource(TileSourceFactory.MAPNIK);
mMapView.setBuiltInZoomControls(true);
mMapView.setMultiTouchControls(true);
mMapController = mMapView.getController();
mMapController.setZoom(13);
GeoPoint point1 = new GeoPoint(var_lat, var_lon);
GeoPoint point2 = new GeoPoint(52.120310618246236, 9.905589604799236); // centre map
GeoPoint point3 = new GeoPoint(52.11712212336459, 9.899281049195961);
mMapController.setCenter(point1);
//mMapController.setCenter(point3);
ArrayList<OverlayItem> items = new ArrayList<OverlayItem>(3);
// Put overlay icon on the centre
items.add(new OverlayItem("Here", "SampleDescription", point1));
/* items.add(new OverlayItem("Here", "SampleDescription", point2));
items.add(new OverlayItem("Here", "SampleDescription", point3));*/
ArrayList<GeoPoint> waypoints = new ArrayList<GeoPoint>(3);
waypoints.add(point1);
waypoints.add(point2);
waypoints.add(point3);
// new UpdateRoadTask().execute(waypoints);
if (savedInstanceState == null){
//Test road service at first launch:
getRoadAsync(point1, point2);
} else {
Road mRoad = null;
updateUIWithRoad(mRoad);
}
this.myLocationOverlay = new ItemizedIconOverlay<OverlayItem>(items,
new ItemizedIconOverlay.OnItemGestureListener<OverlayItem>() {
#Override
public boolean onItemSingleTapUp(final int index,
final OverlayItem item) {
return true;
}
#Override
public boolean onItemLongPress(final int index,
final OverlayItem item) {
return false;
}
}, mResourceProxy);
this.mMapView.getOverlays().add(this.myLocationOverlay);
counter--;
return v;
}
return container;}
public void getRoadAsync(GeoPoint start, GeoPoint destination){
ArrayList<GeoPoint> waypoints = new ArrayList<GeoPoint>(2);
waypoints.add(start);
//intermediate waypoints can be added here:
//waypoints.add(new GeoPoint(48.226, -1.9456));
waypoints.add(destination);
new UpdateRoadTask().execute(waypoints);
}
void updateUIWithRoad(Road road){
List<Overlay> mapOverlays = mMapView.getOverlays();
if (roadOverlay != null){
mapOverlays.remove(roadOverlay);
}
if (road.mStatus == Road.STATUS_DEFAULT)
Toast.makeText(mMapView.getContext(), "We have a problem to get the route", Toast.LENGTH_SHORT).show();
roadOverlay = RoadManager.buildRoadOverlay(road, mMapView.getContext());
Overlay removedOverlay = mapOverlays.set(1, roadOverlay);
//we set the road overlay at the "bottom", just above the MapEventsOverlay,
//to avoid covering the other overlays.
mapOverlays.add(removedOverlay);
putRoadNodes(road);
mMapView.invalidate();
}
private void putRoadNodes(Road road){
roadNodes.removeAllItems();
Drawable marker = getResources().getDrawable(R.drawable.marker_node);
int n = road.mNodes.size();
TypedArray iconIds = getResources().obtainTypedArray(R.array.direction_icons);
for (int i=0; i<n; i++){
RoadNode node = road.mNodes.get(i);
String instructions = (node.mInstructions==null ? "" : node.mInstructions);
ExtendedOverlayItem nodeMarker = new ExtendedOverlayItem(
"Step " + (i+1), instructions,
node.mLocation, this);
nodeMarker.setSubDescription(road.getLengthDurationText(node.mLength, node.mDuration));
nodeMarker.setMarkerHotspot(OverlayItem.HotspotPlace.CENTER);
nodeMarker.setMarker(marker);
int iconId = iconIds.getResourceId(node.mManeuverType, R.drawable.ic_empty);
if (iconId != R.drawable.ic_empty){
Drawable icon = getResources().getDrawable(iconId);
nodeMarker.setImage(icon);
}
roadNodes.addItem(nodeMarker);
}
}
/**
* Async task to get the road in a separate thread.
*/
private class UpdateRoadTask extends AsyncTask<Object, Void, Road> {
protected Road doInBackground(Object... params) {
#SuppressWarnings("unchecked")
ArrayList<GeoPoint> waypoints = (ArrayList<GeoPoint>)params[0];
//RoadManager roadManager = new GoogleRoadManager();
RoadManager roadManager = new OSRMRoadManager();
/*
RoadManager roadManager = new MapQuestRoadManager();
Locale locale = Locale.getDefault();
roadManager.addRequestOption("locale="+locale.getLanguage()+"_"+locale.getCountry());
*/
return roadManager.getRoad(waypoints);
}
private void putRoadNodes(Road road){
ItemizedOverlayWithBubble<ExtendedOverlayItem> roadNodes = null;
roadNodes.removeAllItems();
Drawable marker = getResources().getDrawable(R.drawable.marker_node);
int n = road.mNodes.size();
TypedArray iconIds = getResources().obtainTypedArray(R.array.direction_icons);
for (int i=0; i<n; i++){
RoadNode node = road.mNodes.get(i);
String instructions = (node.mInstructions==null ? "" : node.mInstructions);
ExtendedOverlayItem nodeMarker = new ExtendedOverlayItem(
"Step " + (i+1), instructions,
node.mLocation, this);
nodeMarker.setSubDescription(road.getLengthDurationText(node.mLength, node.mDuration));
nodeMarker.setMarkerHotspot(OverlayItem.HotspotPlace.CENTER);
nodeMarker.setMarker(marker);
int iconId = iconIds.getResourceId(node.mManeuverType, R.drawable.ic_empty);
if (iconId != R.drawable.ic_empty){
Drawable icon = getResources().getDrawable(iconId);
nodeMarker.setImage(icon);
}
roadNodes.addItem(nodeMarker);
}
}
}
public void onFinish(Bundle savedInstanceState) {
super.getActivity().finish();
}
public void onDestroy() {
super.onDestroy();
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
}
public int countLines() throws IOException {
File file = new File(Environment.getExternalStorageDirectory().getPath()+"/GPSdata.txt");
InputStream is = new BufferedInputStream(new FileInputStream(file));
try {
byte[] c = new byte[1024];
int readChars = 0;
boolean empty = true;
while ((readChars = is.read(c)) != -1) {
empty = false;
for (int i = 0; i < readChars; ++i) {
if (c[i] == '\n') {
++counter;
}
}
}
return (counter == 0 && !empty) ? 1 : counter;
} finally {
is.close();
}
}
public String readfromFile() {
// Read from file
BufferedReader bufferedReader = null;
// Pattern being checked for lattidude
Pattern p1 = Pattern.compile("[0-9]{1}.[0-9]+");
Matcher m;
// Der Pfad zur Textdatei
File file = new File(Environment.getExternalStorageDirectory()
.getPath() + "/GPSdata.txt");
try {
// Der BufferedReader erwartet einen FileReader.
// Diesen kann man im Konstruktoraufruf erzeugen.
bufferedReader = new BufferedReader(new FileReader(file));
String line;
String str = null;
// null wird bei EOF oder Fehler zurueckgegeben
while ((line = bufferedReader.readLine()) != null) {
// Zeile auf der Konsole ausgeben
// Pattern currently being checked for
m = p1.matcher(line);
if (m.find()) {
str = m.group();
// arrayList1.add(str);
}
System.out.println(line);
s1 = str;
}
} catch (IOException e) {
e.printStackTrace();
} finally {
if (null != bufferedReader) {
try {
bufferedReader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return s1;
}
public String readfromFile2() {
// Read from file
BufferedReader bufferedReader = null;
// Pattern being checked for longitude
Pattern p = Pattern.compile("[0-9]+.[0-9]+");
Matcher m;
// Der Pfad zur Textdatei
File file = new File(Environment.getExternalStorageDirectory()
.getPath() + "/GPSdata.txt");
try {
// Der BufferedReader erwartet einen FileReader.
// Diesen kann man im Konstruktoraufruf erzeugen.
bufferedReader = new BufferedReader(new FileReader(file));
String line;
String str1 = null;
// null wird bei EOF oder Fehler zurueckgegeben
while ((line = bufferedReader.readLine()) != null) {
// Zeile auf der Konsole ausgeben
// Pattern currently being checked for
m = p.matcher(line);
while (m.find()) {
str1 = m.group();
//arrayList2.add(str1);
}
System.out.println(line);
s2 = str1;
}
} catch (IOException e) {
e.printStackTrace();
} finally {
if (null != bufferedReader) {
try {
bufferedReader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return s2;
}
/*public void readLine(){
try {
BufferedReader in = new BufferedReader(new FileReader("GPSdata.txt"));
String zeile = null;
while ((zeile = in.readLine()) != null){
System.out.println("Gelesene Zeile:" + zeile);
}
} catch (IOException ex) {
ex.printStackTrace();
}
}*/
}
and here is the mainfest.xml:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.uadclient"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="14"
android:targetSdkVersion="14" />
<permission
android:name="in.wptrafficanalyzer.LocationGoogleMapV2Demo.permission.MAPS_RECEIVE"
android:protectionLevel="signature"/>
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE"/>
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
<uses-permission android:name="android.permission.INTERACT_ACROSS_USERS_FULL"/>
<uses-permission android:name="android.permission.SET_DEBUG_APP"></uses-permission>
<uses-feature
android:glEsVersion="0x00020000"
android:required="true"/>
<application
android:allowBackup="true"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity
android:name="com.bosch.uadclient.MainMenuActivity"
android:label="#string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<service android:name="com.bosch.uadclient.LocationProviderService" >
</service>
</application>
</manifest>
Best Wishes

Listview is not showing first entry

I am showing all files from server in listview.
Files on server are as follows:
binary.txt/erpTestBench/muneem.php/oglPrahova/permitCore/workOrderTestBench/
Listview is showing all files except binary.txt file.
My listview xml file is as follows:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
>
<TextView
android:id="#+id/path"
android:layout_width="fill_parent"
android:textSize="12dp"
android:layout_height="wrap_content" android:background="#2377ff"/>
<ListView
android:id="#android:id/list"
android:cacheColorHint="#00000000"
android:layout_width="fill_parent"
android:layout_height="70dp"
android:layout_weight="0.85"
android:clickable="false"
android:textSize="30dp"
android:drawSelectorOnTop="false" android:background="#2f3fc8" android:layout_gravity="center"
android:dividerHeight="15dp"/>
<TextView
android:id="#android:id/empty"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:textSize="30dp"
android:text="No Data"
android:layout_weight="0.75"
android:background="#2f3fc8"/>
<LinearLayout
android:orientation="horizontal"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:paddingTop="6dp" android:paddingBottom="6dp" android:gravity="center|center_vertical"
android:id="#+id/linearLayout" android:background="#346684">
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/imageView1"
android:src="#drawable/power"
android:onClick="bt_Quit" android:layout_marginLeft="10dp" android:layout_marginRight="10dp"
android:layout_gravity="center"/>
<ImageView
android:layout_width="80dp"
android:layout_height="fill_parent"
android:id="#+id/imageView4"
android:src="#drawable/back"
android:onClick="back"
android:layout_marginLeft="10dp" android:layout_marginRight="10dp"/>
<ImageView
android:layout_width="71dp"
android:layout_height="fill_parent"
android:id="#+id/imageView2"
android:src="#drawable/home"
android:layout_marginLeft="10dp" android:layout_marginRight="10dp" android:onClick="home"/>
</LinearLayout>
</LinearLayout>
my java file is as follows:
public class serv extends ListActivity {
private String m_urlString="XXXXX";
// private String result;
private List<String> m_item = null;
private List<String> m_path = null;
private String m_root="XXXX";
private String m_result;
private TextView m_myPath;
static private String m_pos;
private String m_backposition;
private String m_fileURL;
int m_downloadedSize = 0;
int m_totalSize = 0;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.file_chooser);
View v= findViewById(R.id.rowtext);
m_myPath = (TextView)findViewById(R.id.path);
m_fileURL="http://192.168.1.30/muneem/";
Http_connection f=new Http_connection();
f.execute("");
}
class Http_connection extends AsyncTask<String, Void, Void> {
private Exception exception;
protected Void doInBackground(String... urls)
{
try
{
URL url= new URL(m_urlString);
HttpURLConnection con=(HttpURLConnection)url.openConnection();
con.setRequestMethod("GET");
con.connect();
int statusCode=con.getResponseCode();
if (statusCode==HttpURLConnection.HTTP_OK){
BufferedReader in= new BufferedReader(new InputStreamReader(con.getInputStream()));
String line;
m_result="";
while ((line=in.readLine())!=null)
{
m_result=m_result+"\n"+line;
}
in.close();
con.disconnect();
runOnUiThread(new Runnable() {
#Override
public void run() {
getDir(m_urlString);
}
});
}
}
catch (MalformedURLException e)
{
// bundle.putString("Error","Problem with URL");
}
catch (IOException e)
{
// bundle.putString("Error","Problem with connection");
}
return null;
}
}
private void getDir(String dirPath)
{
String[] r=m_result.split("/");
m_myPath.setText("Location: " + dirPath);
m_item = new ArrayList<String>();
m_path = new ArrayList<String>();
for (int k=0;k<r.length;k++)
{
if (r[k].contains("."))
{
m_item.add(r[k]);
}
else
{
m_item.add(r[k]+"/");
}
}
ArrayAdapter<String> fileList =
new ArrayAdapter<String>(serv.this, R.layout.row, m_item);
setListAdapter(fileList);
}
Your data goes through a few steps before making it to the ListView, so the source of the problem could be in one of a few different steps. If you debug your code and check the value of m_result at the beginning of getDir(), you can determine where the problem is coming from. If the value is as expected, there's probably an issue in getDir(), whereas if there's a problem with the string, the issue is probably in doInBackground() (and easy to spot if you know what's wrong with the result, as it turned out).