I have achartengine line graph, i successfully for displaying values from json webservice in line graph. But problem is when i callback asynctask then line graph display old values on x y axis. Not displaying the new values. Below is my code.
public void charDeclaration() {
// For chart
LinearLayout layout = (LinearLayout) findViewById(R.id.chart);
if (myChart == null) {
initializeChartNew();
myChart = ChartFactory.getLineChartView(this, dataset,
multiRenderer);
layout.addView(myChart);
} else {
myChart.repaint();
}
}
#SuppressWarnings("deprecation")
private void initializeChartNew() {
// Creating an XYSeries for Income
fromTemp = new XYSeries("Temperature");
for (int i = 0; i < temp_time.size(); i++) {
fromTemp.add(i, Double.parseDouble(temp_details.get(i)));
System.out.println("Temperature Details in Charts "
+ temp_details.get(i));
}
// Creating a dataset to hold each series
dataset = new XYMultipleSeriesDataset();
// Adding Income Series to the dataset
dataset.addSeries(fromTemp);
// Creating XYSeriesRenderer to customize incomeSeries
from_tempRenderer = new XYSeriesRenderer();
from_tempRenderer.setColor(Color.WHITE);
from_tempRenderer.setPointStyle(PointStyle.CIRCLE);
from_tempRenderer.setFillPoints(true);
from_tempRenderer.setLineWidth(2);
from_tempRenderer.setChartValuesTextSize(20);
from_tempRenderer.setDisplayChartValues(true);
// Creating XYSeriesRenderer to customize expenseSeries
// Creating a XYMultipleSeriesRenderer to customize the whole chart
multiRenderer = new XYMultipleSeriesRenderer();
multiRenderer.setMargins(new int[] { 50, 50, 50, 50 });
multiRenderer.setYLabelsAlign(Align.RIGHT);
multiRenderer.setAxisTitleTextSize(20);
multiRenderer.setChartTitleTextSize(20);
multiRenderer.setLabelsTextSize(18);
multiRenderer.setLegendTextSize(18);
multiRenderer.setXLabels(0);
for (int k = 0; k < temp_date.size(); k++) {
multiRenderer.setChartTitle(temp_date.get(k));
System.out
.println("Temperature Date in Charts " + temp_date.get(k));
}
multiRenderer.setXTitle("Time");
multiRenderer.setYTitle("Temperature");
multiRenderer.setYLabelsPadding(5);
multiRenderer.setZoomButtonsVisible(true);
multiRenderer.setPointSize(5);
for (int i = 0; i < temp_time.size(); i++) {
multiRenderer.addXTextLabel(i, temp_time.get(i));
}
System.out.println("value of temp_details " + temp_details.size());
multiRenderer.removeSeriesRenderer(from_tempRenderer);
multiRenderer.addSeriesRenderer(from_tempRenderer);
}
Below is my AsyncTask
private class TemperatureDetails extends AsyncTask<String, String, String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(MainActivity_New.this);
pDialog.setMessage("Please Wait...");
pDialog.setCancelable(false);
pDialog.setIndeterminate(false);
pDialog.setCanceledOnTouchOutside(false);
pDialog.show();
// building_segment_id="";
/*
* temp_details.clear(); date_time.clear(); temp_date.clear();
* temp_time.clear();
*/
}
#Override
protected String doInBackground(String... params) {
// TODO Auto-generated method stub
try {
System.out
.println("Temp Building Seg ID" + building_segment_id);
// String temperature_url =
// "http://www.intelatrek.com:98/Service1.svc/TempratueList?BeconID=329%20King&Date=2015-04-09";
String temp_url = "http://db.stat-systems.co.nz:81/Service1.svc/TempratureList?BeconID="
+ building_segment_id + "&Date=2015-04-13";
System.out.println("BlucatID in Asynctask " + blucat_id);
System.out.println("building_segment_id in AsyncTask "
+ building_segment_id);
temp_details.clear();
date_time.clear();
temp_date.clear();
temp_time.clear();
JSONObject jObject = JSONParser.getJsonFromURL(temp_url);
tempjsonflag = jObject.getString("Flag");
JSONArray jArray = jObject.getJSONArray("TempTransList");
for (int i = 0; i < jArray.length(); i++) {
JSONObject job = jArray.getJSONObject(i);
String BuildingId = job.getString("BuildingId");
String BuildingSegmentId = job
.getString("BuildingSegmentId");
// String Customer_ID = job.getString("Customer_ID");
String DateTime = job.getString("DateTime");
// String InnerLocationId =
// job.getString("InnerLocationId");
String Temp_Date = job.getString("TempDate");
String Temp_Time = job.getString("TempTime");
String Temperature = job.getString("Temperature");
temp_details.add(Temperature);
date_time.add(DateTime);
temp_date.add(Temp_Date);
temp_time.add(Temp_Time);
}
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(String result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
if (pDialog != null) {
pDialog.dismiss();
}
for (int i = 0; i < temp_details.size(); i++) {
System.out
.println("Temperature Details " + temp_details.get(i));
System.out.println("Temperature Date Time " + date_time.get(i));
System.out.println("Temperature Temp Date " + temp_date.get(i));
System.out.println("Temperature Temp Time " + temp_time.get(i));
}
System.out.println("Temp Details " + temp_details.size());
System.out.println("Temp Date Time " + date_time.size());
System.out.println("Temp Temp Date " + temp_date.size());
System.out.println("Temp Temp Time " + temp_time.size());
System.out.println("Temp JSON FLAG " + tempjsonflag);
// if(tempjsonflag.equals("Success")){
if (tempe_detail.toString().equals("")) {
temp_textview_temperature.setVisibility(View.GONE);
temp_textview_notfound.setVisibility(View.VISIBLE);
imageview_degree.setVisibility(View.GONE);
/*
* LinearLayout layout = (LinearLayout)
* findViewById(R.id.chart);
*/
chart.setVisibility(View.GONE);
} else {
temp_textview_notfound.setVisibility(View.GONE);
temp_textview_temperature.setVisibility(View.VISIBLE);
temp_textview_temperature.setText(tempe_detail);
temp_textview_temperature.setTextSize(70);
imageview_degree.setVisibility(View.VISIBLE);
// temp_textview_temperature.setLayoutParams(llp);
/*
* LinearLayout layout = (LinearLayout)
* findViewById(R.id.chart);
*/
chart.setVisibility(View.VISIBLE);
charDeclaration();
}
if (temp_textview_temperature.getText().toString().equals("1")) {
temp_textview_temperature.setPadding(25, 0, 0, 0);
} else if (temp_textview_temperature.getText().toString()
.equals("2")) {
temp_textview_temperature.setPadding(25, 0, 0, 0);
} else if (temp_textview_temperature.getText().toString()
.equals("3")) {
temp_textview_temperature.setPadding(25, 0, 0, 0);
} else if (temp_textview_temperature.getText().toString()
.equals("4")) {
temp_textview_temperature.setPadding(25, 0, 0, 0);
} else if (temp_textview_temperature.getText().toString()
.equals("5")) {
temp_textview_temperature.setPadding(25, 0, 0, 0);
} else if (temp_textview_temperature.getText().toString()
.equals("6")) {
temp_textview_temperature.setPadding(25, 0, 0, 0);
} else if (temp_textview_temperature.getText().toString()
.equals("7")) {
temp_textview_temperature.setPadding(25, 0, 0, 0);
} else if (temp_textview_temperature.getText().toString()
.equals("8")) {
temp_textview_temperature.setPadding(25, 0, 0, 0);
} else if (temp_textview_temperature.getText().toString()
.equals("9")) {
temp_textview_temperature.setPadding(25, 0, 0, 0);
} else {
temp_textview_temperature.setPadding(0, 0, 0, 0);
}
int dip = (int) TypedValue.applyDimension(
TypedValue.COMPLEX_UNIT_DIP, (float) 1, getResources()
.getDisplayMetrics());
DisplayMetrics dm = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(dm);
int widthPixels = dm.widthPixels;
int heightPixels = dm.widthPixels;
float scaleFactor = dm.density;
float widthInches = widthPixels / scaleFactor;
if (widthInches >= 720) {
// 10" tablet resolutions
if (tempe_detail.toString().equals("")) {
temp_textview_temperature.setVisibility(View.GONE);
temp_textview_notfound.setVisibility(View.VISIBLE);
imageview_degree.setVisibility(View.GONE);
// temp_textview_notfound.setText(60);
chart.setVisibility(View.GONE);
} else {
temp_textview_notfound.setVisibility(View.GONE);
temp_textview_temperature.setVisibility(View.VISIBLE);
temp_textview_temperature.setText(tempe_detail);
if (getResources().getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE) {
// Do some stuff
temp_textview_temperature.setTextSize(70);
imageview_degree.getLayoutParams().height = 30;
imageview_degree.getLayoutParams().width = 30;
} else {
temp_textview_temperature.setTextSize(180);
imageview_degree.getLayoutParams().height = 50;
imageview_degree.getLayoutParams().width = 50;
}
imageview_degree.setVisibility(View.VISIBLE);
// temp_textview_temperature.setLayoutParams(llp);
chart.setVisibility(View.VISIBLE);
charDeclaration();
}
if (temp_textview_temperature.getText().toString()
.matches("[0-9.]*")) {
temp_textview_temperature.setPadding(0, 0, 0, 0);
} else if (temp_textview_temperature.getText().length() == 3) {
temp_textview_temperature.setPadding(20, 0, 0, 0);
} else {
temp_textview_temperature.setPadding(0, 0, 0, 0);
}
} else if (widthInches >= 600) {
// 7" tablet resolutions
if (tempe_detail.toString().equals("")) {
temp_textview_temperature.setVisibility(View.GONE);
temp_textview_notfound.setVisibility(View.VISIBLE);
imageview_degree.setVisibility(View.GONE);
chart.setVisibility(View.GONE);
} else {
temp_textview_notfound.setVisibility(View.GONE);
temp_textview_temperature.setVisibility(View.VISIBLE);
temp_textview_temperature.setText(tempe_detail);
temp_textview_temperature.setTextSize(140);
imageview_degree.setVisibility(View.VISIBLE);
// temp_textview_temperature.setLayoutParams(llp);
chart.setVisibility(View.VISIBLE);
charDeclaration();
}
if (temp_textview_temperature.getText().toString()
.matches("[0-9.]*")) {
temp_textview_temperature.setPadding(25, 0, 0, 0);
if (temp_textview_temperature.getText().length() == 3) {
temp_textview_temperature.setPadding(0, 0, 0, 0);
}
}
else {
temp_textview_temperature.setPadding(0, 0, 0, 0);
}
}
// }
}
}
use myChart.repaint(); to redraw your chart after date has been changed , if repaint doesn't work so before repainting the chart try using removeAllViews() to chart's parent layout.
chartlayout.removeAllViews();
Related
In CameraX Analysis, setTargetResolution(new Size(2560, 800), but in Analyzer imageProxy.getImage.getWidth=1280 and getHeight=400, and YUVToByte(imageProxy.getImage).length()=768000。In Camera, parameter.setPreviewSize(2560, 800) then byte[].length in onPreviewFrame is 3072000(equales 768000*(2560/1280)*(800/400))。How can I make CameraX Analyzer imageProxy.getImage.getWidth and getHeight = 2560 and 800, and YUVToByte(ImageProxy.getImage).length()=3072000? In CameraX onPreviewFrame(), res always = null, in Camera onPreviewFrame(), res can get currect value, what's the different between CameraX and Camera? And what should I do in CameraX?
CameraX:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main2);
try {
copyDataBase();
} catch (IOException e) {
e.printStackTrace();
}
getSupportActionBar().hide();
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
viewFinder = findViewById(R.id.previewView);
executor = Executors.newSingleThreadExecutor();
if (!allPermissionGranted()) {
ActivityCompat.requestPermissions(this, REQUIRED_PERMISSIONS, REQUEST_CODE_PERMISSIONS);
}
DisplayMetrics metric = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(metric);
width = metric.widthPixels;
height = metric.heightPixels;
l = 100;
r = width - 100;
ntmpH = (r - l) * 58 / 100;
t = (height - ntmpH) / 2;
b = t + ntmpH;
double proportion = (double) width / (double) preHeight;
double hproportion = (double) height / (double) preWidth;
l = (int) (l / proportion);
t = (int) (t / hproportion);
r = (int) (r / proportion);
b = (int) (b / hproportion);
m_ROI[0] = l;
m_ROI[1] = t;
m_ROI[2] = r;
m_ROI[3] = b;
cameraProviderFuture = processCameraProvider.getInstance(this);
cameraProviderFuture.addListener(() -> {
try {
ProcessCameraProvider cameraProvider = cameraProviderFuture.get();
#SuppressLint("RestrictedApi") Preview preview = new Preview.Builder().build();
CameraSelector cameraSelector = new CameraSelector.Builder().
requireLensFacing(CameraSelector.LENS_FACING_BACK).build();
ImageAnalysis imageAnalysis = new ImageAnalysis.Builder()
.setTargetResolution(new Size(2560, 800))
.setBackpressureStrategy(ImageAnalysis.STRATEGY_KEEP_ONLY_LATEST)
.setTargetRotation(Surface.ROTATION_90)
.build();
imageAnalysis.setAnalyzer(executor, new ImageAnalysis.Analyzer() {
#SuppressLint("UnsafeExperimentalUsageError")
#Override
public void analyze(#NonNull ImageProxy imageProxy) {
if (imageProxy.getFormat() == ImageFormat.YUV_420_888) {
image = imageProxy.getImage();
bIninKernal();
Log.d("Size ", image.getWidth() + "/" + image.getHeight());
onPreviewFrame(YUVToByte(image));
} else {
Log.d("Status ", "照片格式錯誤" + imageProxy.getFormat());
}
imageProxy.close();
}
});
cameraProvider.bindToLifecycle(this, cameraSelector, preview, imageAnalysis);
preview.setSurfaceProvider(viewFinder.createSurfaceProvider());
} catch (ExecutionException | InterruptedException e) {
e.printStackTrace();
}
}, ContextCompat.getMainExecutor(this));
}
#NonNull
#Override
public CameraXConfig getCameraXConfig() {
return Camera2Config.defaultConfig();
}
private boolean allPermissionGranted() {
for (String permission : REQUIRED_PERMISSIONS) {
if (ContextCompat.checkSelfPermission(this, permission) != PackageManager.PERMISSION_GRANTED) {
return false;
}
}
return true;
}
private byte[] YUVToByte(Image image) {
Image.Plane[] planes = image.getPlanes();
ByteBuffer buffer0 = planes[0].getBuffer();
ByteBuffer buffer1 = planes[1].getBuffer();
ByteBuffer buffer2 = planes[2].getBuffer();
int width = image.getWidth();
int height = image.getHeight();
byte[] data = new byte[image.getWidth() * image.getHeight() * ImageFormat.getBitsPerPixel(ImageFormat.YUV_420_888) / 8];
byte[] rowData1 = new byte[planes[1].getRowStride()];
byte[] rowData2 = new byte[planes[2].getRowStride()];
int bytesPerPixel = ImageFormat.getBitsPerPixel(ImageFormat.YUV_420_888) / 8;
// loop via rows of u/v channels
int offsetY = 0;
int sizeY = width * height * bytesPerPixel;
int sizeUV = (width * height * bytesPerPixel) / 4;
for (int row = 0; row < height; row++) {
// fill data for Y channel, two row
{
int length = bytesPerPixel * width;
buffer0.get(data, offsetY, length);
if (height - row != 1)
buffer0.position(buffer0.position() + planes[0].getRowStride() - length);
offsetY += length;
}
if (row >= height / 2)
continue;
{
int uvlength = planes[1].getRowStride();
if ((height / 2 - row) == 1) {
uvlength = width / 2 - planes[1].getPixelStride() + 1;
}
buffer1.get(rowData1, 0, uvlength);
buffer2.get(rowData2, 0, uvlength);
// fill data for u/v channels
for (int col = 0; col < width / 2; ++col) {
// u channel
data[sizeY + (row * width) / 2 + col] = rowData1[col * planes[1].getPixelStride()];
// v channel
data[sizeY + sizeUV + (row * width) / 2 + col] = rowData2[col * planes[2].getPixelStride()];
}
}
}
return data;
}
private void bIninKernal() {
api = new LPR();
String FilePath = Environment.getExternalStorageDirectory().toString() + "/lpr.key";
int nRet = api.Init(this, m_ROI[0], m_ROI[1], m_ROI[2], m_ROI[3], preHeight, preWidth, FilePath);
if (nRet != 0) {
bInitKernal = false;
Log.d("Status ", "相機開啟失敗");
} else {
bInitKernal = true;
}
}
private void onPreviewFrame(byte[] data) {
bIninKernal();
tackData = data;
Log.d("data length ", data.length + "");
resultStr = "";
if (!leaving && bInitKernal) {
byte[] result;
String res = "";
result = api.VideoRec(tackData, 1280, 400, 1);
try {
res = new String(result, "gb2312");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
if (res != null && !"".equals(res.trim())) {
resultStr = res.trim();
if (resultStr != "") {
leaving = true;
MediaActionSound sound = new MediaActionSound();
sound.play(MediaActionSound.SHUTTER_CLICK);
Log.d("Status ", "辨識成功");
Log.d("車牌號碼", resultStr);
Thread thread = new Thread(Image_update);
thread.start();
try {
thread.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
Intent intent = new Intent(MainActivity2.this, MainActivity.class);
intent.putExtra("result", resultStr);
Log.d("result", resultStr);
setResult(1, intent);
finish();
}
} else {
Log.d("Status ", "未分辨車牌號碼,請重拍");
}
}
}
public void copyDataBase() throws IOException {
// Common common = new Common();
// 取得SK卡路徑/lpr.key
String dst = Environment.getExternalStorageDirectory().toString() + "/lpr.key";
File file = new File(dst);
if (!file.exists()) {
// file.createNewFile();
} else {
file.delete();
}
Log.d("File Name", file.toString());
try {
InputStream myInput = getAssets().open("lpr.key");
OutputStream myOutput = new FileOutputStream(dst);
byte[] buffer = new byte[1024];
int length;
while ((length = myInput.read(buffer)) > 0) {
myOutput.write(buffer, 0, length);
}
myOutput.flush();
myOutput.close();
myInput.close();
} catch (Exception e) {
System.out.println("lpr.key" + "is not found");
}
}
private Runnable Image_update = new Runnable() {
Retrofit retrofit = new Retrofit.Builder()
.baseUrl("https://0d9dccd7eac8.ngrok.io/")
.addConverterFactory(GsonConverterFactory.create())
.build();
MyAPIService myAPIService = retrofit.create(MyAPIService.class);
#Override
public void run() {
Log.d("Status ", "run");
Log.d("resultStr ", resultStr);
String url = "D:\\Images\\license_plate\\";
String imgStr = bitmap2base64(toBitmap(image));
LicensePlate licensePlate = new LicensePlate();
licensePlate.setsPlate(resultStr);
licensePlate.setsPicPosition(url + resultStr);
licensePlate.setImgStr(imgStr);
Call<LicensePlate> call = myAPIService.uploadLicensePlate(licensePlate);
call.enqueue(new Callback<LicensePlate>() {
#Override
public void onResponse(Call<LicensePlate> call, Response<LicensePlate> response) {
if(response.isSuccessful()){
Log.d("Status ", "照片上傳成功");
}else{
Log.d("Status ", "照片上傳失敗");
Log.d("response code ", response.code() + "");
}
}
#Override
public void onFailure(Call<LicensePlate> call, Throwable t) {
Log.d("Status ", "onFailure");
Log.d("Message ", t.getMessage());
}
});
}
};
private String bitmap2base64(Bitmap bitmap){
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.PNG, 100, outputStream);
return Base64.encodeToString(outputStream.toByteArray(), Base64.DEFAULT).trim().replaceAll("\n", "").replaceAll("\r", "");
}
private Bitmap toBitmap(Image image) {
Image.Plane[] planes = image.getPlanes();
ByteBuffer yBuffer = planes[0].getBuffer();
ByteBuffer uBuffer = planes[1].getBuffer();
ByteBuffer vBuffer = planes[2].getBuffer();
int ySize = yBuffer.remaining();
int uSize = uBuffer.remaining();
int vSize = vBuffer.remaining();
byte[] nv21 = new byte[ySize + uSize + vSize];
//U and V are swapped
yBuffer.get(nv21, 0, ySize);
vBuffer.get(nv21, ySize, vSize);
uBuffer.get(nv21, ySize + vSize, uSize);
YuvImage yuvImage = new YuvImage(nv21, ImageFormat.NV21, image.getWidth(), image.getHeight(), null);
ByteArrayOutputStream out = new ByteArrayOutputStream();
yuvImage.compressToJpeg(new Rect(0, 0, yuvImage.getWidth(), yuvImage.getHeight()), 75, out);
byte[] imageBytes = out.toByteArray();
return BitmapFactory.decodeByteArray(imageBytes, 0, imageBytes.length);
}
}
Camera
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);// 隐藏标题
DisplayMetrics metric = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(metric);
int metricwidth = metric.widthPixels; // 屏幕宽度(像素)
int metricheight = metric.heightPixels; // 屏幕高度(像素)
try {
copyDataBase();
} catch (IOException e) {
e.printStackTrace();
}
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);// 竖屏
Configuration cf= this.getResources().getConfiguration(); //获取设置的配置信息
int noriention=cf.orientation;
requestWindowFeature(Window.FEATURE_NO_TITLE);// 隐藏标题
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);// 设置全屏
// // 屏幕常亮
getWindow().setFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON,
WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
setContentView(R.layout.activity_lpr2);
findView();
}
private void findView() {
surfaceView = (SurfaceView) findViewById(R.id.surfaceView);
re_c = (RelativeLayout) findViewById(R.id.re_c);
DisplayMetrics metric = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(metric);
width = metric.widthPixels; // 屏幕宽度(像素)
height = metric.heightPixels; // 屏幕高度(像素)
if(myView==null)
{
if (isFatty)
{
myView = new LPRfinderView2(LPR2Activity.this, width, height, isFatty);
}
else
{
myView = new LPRfinderView2(LPR2Activity.this, width, height);
}
re_c.addView(myView);
}
surfaceHolder = surfaceView.getHolder();
surfaceHolder.addCallback(LPR2Activity.this);
surfaceHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
surfaceView.setFocusable(true);
//surfaceView.invali.date();
}
public void copyDataBase() throws IOException {
// Common common = new Common();
// 取得SK卡路徑/lpr.key
String dst = Environment.getExternalStorageDirectory().toString() + "/lpr.key";
File file = new File(dst);
if (!file.exists()) {
// file.createNewFile();
} else {
file.delete();
}
Log.d("File Name", file.toString());
try {
InputStream myInput = getAssets().open("lpr.key");
OutputStream myOutput = new FileOutputStream(dst);
byte[] buffer = new byte[1024];
int length;
while ((length = myInput.read(buffer)) > 0) {
myOutput.write(buffer, 0, length);
}
myOutput.flush();
myOutput.close();
myInput.close();
} catch (Exception e) {
System.out.println("lpr.key" + "is not found");
}
}
public void surfaceCreated(SurfaceHolder holder) {
if (mycamera == null) {
try {
mycamera = Camera.open();
} catch (Exception e) {
e.printStackTrace();
String mess = "打开摄像头失败";
Toast.makeText(getApplicationContext(), mess, Toast.LENGTH_LONG).show();
return;
}
}
if(mycamera!=null)
{
try {
mycamera.setPreviewDisplay(holder);
timer2 = new Timer();
if (timer == null)
{
timer = new TimerTask()
{
public void run()
{
if (mycamera != null)
{
try
{
mycamera.autoFocus(new AutoFocusCallback()
{
public void onAutoFocus(boolean success, Camera camera)
{
}
});
}
catch (Exception e)
{
e.printStackTrace();
}
}
};
};
}
timer2.schedule(timer, 500, 2500);
initCamera();
//mycamera.startPreview();
//mycamera.autoFocus(null);
} catch (IOException e) {
e.printStackTrace();
}
}
if(api==null)
{
api= new LPR();
String FilePath =Environment.getExternalStorageDirectory().toString()+"/lpr.key";
int nRet = api.Init(this,m_ROI[0], m_ROI[1], m_ROI[2], m_ROI[3], preHeight, preWidth,FilePath);
if(nRet!=0)
{
Toast.makeText(getApplicationContext(), "啟動失敗,請調整時間", Toast.LENGTH_SHORT).show();
Log.d("nRet ", nRet + "");
bInitKernal =false;
}
else
{
bInitKernal=true;
}
}
if(alertDialog==null){
alertDialog = new AlertDialog.Builder(this).create();
alertDialoginfo = new AlertDialog.Builder(this).create();
}
}
#Override
public void surfaceChanged(final SurfaceHolder holder, int format, int width, int height) {
}
#Override
public void surfaceDestroyed(SurfaceHolder holder) {
try {
if (mycamera != null) {
mycamera.setPreviewCallback(null);
mycamera.stopPreview();
mycamera.release();
mycamera = null;
}
} catch (Exception e) {
}
if(bInitKernal){
bInitKernal=false;
api = null;
}
if(toast!=null){
toast.cancel();
toast = null;
}
if(timer2!=null){
timer2.cancel();
timer2=null;
}
if(alertDialog!=null)
{
alertDialog.dismiss();
alertDialog.cancel();
alertDialog=null;
}
}
#Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_BACK) {
try {
if (mycamera != null) {
mycamera.setPreviewCallback(null);
mycamera.stopPreview();
mycamera.release();
mycamera = null;
}
} catch (Exception e) {
e.printStackTrace();
}
if(bInitKernal)
{
bInitKernal=false;
api = null;
}
finish();
if(toast!=null){
toast.cancel();
toast=null;
}
if(timer2!=null){
timer2.cancel();
timer2=null;
}
if(alertDialog!=null)
{
alertDialog.cancel();
alertDialog=null;
}
}
return super.onKeyDown(keyCode, event);
}
#TargetApi(14)
private void initCamera() {
Camera.Parameters parameters = mycamera.getParameters();
List<Camera.Size> list = parameters.getSupportedPreviewSizes();
preWidth = list.get(4).width;
preHeight = list.get(4).height;
parameters.setPictureFormat(PixelFormat.JPEG);
parameters.setPreviewSize(preWidth,preHeight);
if (!bROI) {
int l,t,r,b;
l = 100;
r = width-100;
int ntmpH =(r-l)*58/100;
t = (height-ntmpH)/2;
b = t+ntmpH;
double proportion = (double) width / (double) preHeight;
double hproportion=(double)height/(double) preWidth;
l = (int) (l /proportion);
t = (int) (t /hproportion);
r = (int) (r /proportion);
b = (int) (b / hproportion);
m_ROI[0]=l;
m_ROI[1]=t;
m_ROI[2]=r;
m_ROI[3]=b;
bROI = true;
}
if (parameters.getSupportedFocusModes().contains(
parameters.FOCUS_MODE_AUTO))
{
parameters.setFocusMode(Camera.Parameters.FOCUS_MODE_AUTO);// 1连续对焦
}
mycamera.setPreviewCallback(LPR2Activity.this);
mycamera.setParameters(parameters);
mycamera.setDisplayOrientation(90); //一般機種
mycamera.startPreview();
}
public void onPreviewFrame(byte[] data, Camera camera) {
tackData = data;
Log.d("data length ", data.length + "");
ByteArrayInputStream bis = new ByteArrayInputStream(data);
resultStr = "";
if (!leaving&& bInitKernal ) {
Log.d("Status ", "開始判斷");
byte result[];//[] = new byte[10];
String res="";
result = api.VideoRec(tackData, preWidth, preHeight, 1);
Log.d("preWidth ", preWidth + "");
Log.d("preHeight", preHeight + "");
Log.d("width ", width + "");
Log.d("height", height + "");
try {
res = new String(result,"gb2312");
Log.d("try ", res);
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
Log.d("Exception ", e.getMessage());
e.printStackTrace();
}
Log.d("res ", res);
if(res!=null&&!"".equals(res.trim()))
{
Camera.Parameters parameters = mycamera.getParameters();
resultStr =res.trim();
if (resultStr != "") {
leaving = true;
//拍照音效
MediaActionSound sound = null;
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.JELLY_BEAN) {
sound = new MediaActionSound();
sound.play(MediaActionSound.SHUTTER_CLICK);
}
Intent intent = new Intent();
intent.putExtra("strPltNo",resultStr);
setResult(2,intent);
finish();
}else{
Log.d("Status ", "未分配車牌號碼,請重拍");
}
}
}
}
#RequiresApi(api = Build.VERSION_CODES.CUPCAKE)
public String pictureName() {
String str = "";
Time t = new Time();
t.setToNow(); // 取得系统时间。
int year = t.year;
int month = t.month + 1;
int date = t.monthDay;
int hour = t.hour; // 0-23
int minute = t.minute;
int second = t.second;
if (month < 10)
str = String.valueOf(year) + "0" + String.valueOf(month);
else {
str = String.valueOf(year) + String.valueOf(month);
}
if (date < 10)
str = str + "0" + String.valueOf(date + "_");
else {
str = str + String.valueOf(date + "_");
}
if (hour < 10)
str = str + "0" + String.valueOf(hour);
else {
str = str + String.valueOf(hour);
}
if (minute < 10)
str = str + "0" + String.valueOf(minute);
else {
str = str + String.valueOf(minute);
}
if (second < 10)
str = str + "0" + String.valueOf(second);
else {
str = str + String.valueOf(second);
}
return str;
}
public void Leave(View view) {
Intent intent = new Intent();
intent.putExtra("strPltNo","");
setResult(3,intent);
finish();
}
}
CameraX Log
Camera Log
With regards to the image analysis resolution, the documentation of ImageAnalysis.Builder.setTargetResolution() states that:
The maximum available resolution that could be selected for an
ImageAnalysis is limited to be under 1080p.
So setting a size of 2560x800 won't work as you expect. In return CameraX seems to be selecting the maximum ImageAnalysis resolution that has the same aspect ratio you requested (2560/800 = 1280/400).
here is my code:
public class TrainingActivity extends Activity {
private EditText etIn1, etIn2, etDesired;
private TextView prevInput;
int W[][] = new int[2][];
int X[][] = new int[30][];
int w0=0, w1=0, w2=0, p=1, sum=0, clicks=0;
private Button nxtData;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.training_activity);
View backgroundImage = findViewById(R.id.background);
Drawable background = backgroundImage.getBackground();
background.setAlpha(40);
etIn1= (EditText) findViewById(R.id.etInput1);
etIn2 = (EditText) findViewById(R.id.etInput2);
etDesired = (EditText) findViewById(R.id.etDesired);
prevInput = (TextView) findViewById(R.id.prevInput);
nxtData = (Button) findViewById(R.id.nextData);
nxtData.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
int sum = 0;
++clicks;
int intetIn1 = Integer.parseInt(etIn1.getText().toString());
int intetIn2 = Integer.parseInt(etIn2.getText().toString());
int intetDesired = Integer.parseInt(etDesired.getText().toString());
X[clicks-1] = new int[] {intetIn1, intetIn2, 1};
prevInput.setText("Last Inputs: (" + intetIn1 + ", " + intetIn2 +
", " + intetDesired + ")");
if(clicks == 1) {
if(intetDesired == 1) {
W[0] = new int[] {intetIn1, intetIn2, 1};
W[1] = W[0];
} else if(intetDesired == (-1)){
W[0] = new int[] {-intetIn1, -intetIn2, -1};
W[1] = W[0];
}
} else if(clicks > 1) {
for(int i=0; i<3; i++){
sum = sum + W[clicks-1][i] * X[clicks-1][i];
} if(sum>0 && intetDesired==1) {
W[clicks] = W[clicks-1];
} else if(sum<0 && intetDesired==(-1)) {
W[clicks] = W[clicks-1];
} else if(sum<=0 && intetDesired==1) {
for(int i=0; i<3; i++) {
W[clicks][i] = W[clicks-1][i] + X[clicks-1][i];
}
} else if(sum>=0 && intetDesired==(-1)) {
for(int i=0; i<3; i++) {
W[clicks][i] = W[clicks-1][i] - X[clicks-1][i];
}
}
}
Toast.makeText(getApplicationContext(), "" + clicks,
Toast.LENGTH_SHORT).show();
System.out.println(X[0][0]);
etIn1.setText("");
etIn2.setText("");
etDesired.setText("");
}
});
}}
and here is the Exception:
java.lang.ArrayIndexOutOfBoundsException: length=2; index=2
the clicks is the number of times that user click the button. at first it's ok but when i try and add some more inputs it crashes. can you tell why this is happening?
index of array is always less than length as index starts form 0 whereas length from 1 therefore X[clicks-1] is causing the problem
What is the initial value of click variable.
Can you post more code related. And for the first time if click is 0 then
X[clicks-1] = new int[] {intetIn1, intetIn2, 1};
this says you are store these value at click-1 th position which is not even initialized.. so
int X[] = new int[]{intetIn1, intetIn2, 1};
would be better.
I have seen many answers on this issue which has not worked so far for me, the best option I got was using a Picasso to solve this, I have imported the .jar but am getting an error on the code I was told to use, I get an error on this(context) in the following line of code, say (context) cannot be resolved to a variable
Picasso.with(context).load(myBitmap).into(imageView);
This is the lines of code that generates the error, which I intend solving using Picasso
File imgFile = new File(data.get(position).get("path"));
Bitmap myBitmap = BitmapFactory.decodeFile(imgFile.getAbsolutePath());
imageView.setImageBitmap(myBitmap);
This is my full code below
public class WidgetActivity extends Activity {
GridView grid;
Matrix matrix = new Matrix();
Bitmap rotateimage;
ArrayList<HashMap<String, String>> maplist = new ArrayList<HashMap<String,String>>();
LocalStorageHandler notedb;
ImageView iv_notes;
EditText content;
LinearLayout grid_layout;
AppWidgetManager appWidgetManager;
int n;
Intent i;
int s;
String[] tcolor;
public String path = "", name = "", color = "";
public void onCreate(Bundle os) {
super.onCreate(os);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.dialog_shownotes);
notedb = new LocalStorageHandler(WidgetActivity.this);
grid = (GridView) findViewById(R.id.grid);
iv_notes = (ImageView) findViewById(R.id.iv_note);
content = (EditText) findViewById(R.id.content);
grid_layout = (LinearLayout) findViewById(R.id.grid_layout);
i = getIntent();
n = i.getIntExtra("currentWidgetId", 1);
new getlist().execute();
}
class getlist extends AsyncTask<String, String, String> {
ArrayList<HashMap<String, String>> maplist = new ArrayList<HashMap<String, String>>();
#Override
public void onPreExecute() {
super.onPreExecute();
}
#Override
protected String doInBackground(String... arg) {
ArrayList<String> filepaths = new ArrayList<String>();
ArrayList<String> filenames = new ArrayList<String>();
Cursor dbCursor = notedb.get();
if (dbCursor.getCount() > 0) {
int noOfScorer = 0;
dbCursor.moveToFirst();
while ((!dbCursor.isAfterLast())
&& noOfScorer < dbCursor.getCount()) {
noOfScorer++;
try {
HashMap<String, String> items = new HashMap<String, String>();
filepaths.add(Environment.getExternalStorageDirectory()
+ "/360notes/" + dbCursor.getString(2));
filenames.add(dbCursor.getString(3));
items.put("path",
Environment.getExternalStorageDirectory()
+ "/360notes/" + dbCursor.getString(2));
items.put("name", dbCursor.getString(3));
items.put("time", dbCursor.getString(1));
items.put("id", dbCursor.getString(0));
items.put("color", dbCursor.getString(4));
maplist.add(items);
} catch (Exception e) {
e.printStackTrace();
}
dbCursor.moveToNext();
}
}
return null;
}
#Override
protected void onPostExecute(String unused) {
if (maplist.size() > 0) {
grid.setAdapter(new GridViewImageAdapter(WidgetActivity.this,
maplist));
}
}
}
public class GridViewImageAdapter extends BaseAdapter {
private Activity _activity;
ArrayList<String> _filenames = new ArrayList<String>();
private ArrayList<HashMap<String, String>> data = new ArrayList<HashMap<String, String>>();
public GridViewImageAdapter(Activity activity,
ArrayList<HashMap<String, String>> items) {
this._activity = activity;
data = items;
}
#Override
public int getCount() {
return data.size();
}
#Override
public Object getItem(int position) {
return position;
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(final int position, View convertView,
ViewGroup parent) {
LayoutInflater inflate = (LayoutInflater) _activity
.getSystemService(_activity.LAYOUT_INFLATER_SERVICE);
convertView = inflate.inflate(R.layout.show_image, null);
ImageView imageView = (ImageView) convertView
.findViewById(R.id.imgScreen);
TextView title = (TextView) convertView.findViewById(R.id.title);
try {
String[] tcolor = data.get(position).get("name").split(" / ");
title.setText(tcolor[0].trim());
title.setTextColor(Color.parseColor(tcolor[1].trim()));
if (tcolor[2].trim().equals("0")) {
String text = title.getText().toString();
SpannableString span = new SpannableString(text);
span.setSpan(new UnderlineSpan(), 0, span.length(), 0);
// title.setText(span);
} else if (tcolor[2].trim().equals("3")) {
// title.setTypeface(null, Typeface.BOLD);
String text = title.getText().toString();
SpannableString span = new SpannableString(text);
span.setSpan(new UnderlineSpan(), 0, span.length(), 0);
// title.setText(span);
} else if (tcolor[2].trim().equals("4")) {
// title.setTypeface(null, Typeface.ITALIC);
String text = title.getText().toString();
SpannableString span = new SpannableString(text);
span.setSpan(new UnderlineSpan(), 0, span.length(), 0);
// title.setText(span);
} else if (tcolor[2].trim().equals("1")) {
// title.setTypeface(null, Typeface.BOLD);
String text = title.getText().toString();
SpannableString span = new SpannableString(text);
span.removeSpan(text);
} else if (tcolor[2].trim().equals("2")) {
// title.setTypeface(null, Typeface.ITALIC);
String text = title.getText().toString();
SpannableString span = new SpannableString(text);
span.removeSpan(text);
} else {
String text = title.getText().toString();
SpannableString span = new SpannableString(text);
span.removeSpan(text);
}
} catch (IndexOutOfBoundsException e) {
// TODO: handle exception
}
// TODO: handle exception
BitmapFactory.Options options = new BitmapFactory.Options();
options.inSampleSize = 4;
File imgFile = new File(data.get(position).get("path"));
Bitmap myBitmap = BitmapFactory.decodeFile(imgFile.getAbsolutePath());
imageView.setImageBitmap(myBitmap);
/*if (myBitmap != null && !myBitmap.isRecycled()) {
myBitmap.recycle();
myBitmap = null;
}*/
//myBitmap.recycle();
//myBitmap = null;
Picasso.with(context).load(myBitmap).into(imageView);
grid.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
grid.setVisibility(View.GONE);
// grid_layout.setVisibility(View.VISIBLE);
s = position;
path = data.get(position).get("path");
try {
tcolor = data.get(position).get("name").split(" / ");
name = tcolor[0].trim();
color = tcolor[1].trim();
} catch (IndexOutOfBoundsException e) {
name = "";
color = "#000000";
}
appWidgetManager = AppWidgetManager
.getInstance(WidgetActivity.this);
UnreadWidgetProvider.updateWidget(WidgetActivity.this,
appWidgetManager, n, path,
data.get(position).get("name"), color, s);
finish();
}
});
return convertView;
}
}
public void images(String path, String name, String color) {
try {
Bitmap bm;
try {
bm = decodeSampledBitmapFromResource(path);
ExifInterface exifReader = new ExifInterface(path);
int orientation = exifReader.getAttributeInt(
ExifInterface.TAG_ORIENTATION, -1);
if (orientation == ExifInterface.ORIENTATION_NORMAL) {
matrix.postRotate(360);
} else if (orientation == ExifInterface.ORIENTATION_ROTATE_90) {
// matrix.postRotate(90);
} else if (orientation == ExifInterface.ORIENTATION_ROTATE_180) {
// matrix.postRotate(180);
} else if (orientation == ExifInterface.ORIENTATION_ROTATE_270) {
// matrix.postRotate(270);
} else if (orientation == ExifInterface.ORIENTATION_UNDEFINED) {
// matrix.postRotate(90);
} else {
}
rotateimage = Bitmap.createBitmap(bm, 0, 0, bm.getWidth(),
bm.getHeight(), matrix, true);
iv_notes.setImageBitmap(rotateimage);
content.setText(name);
content.setFocusable(false);
try {
String[] tcolor = name.split(" / ");
content.setText(tcolor[0].trim());
content.setTextColor(Color.parseColor(tcolor[1].trim()));
if (tcolor[2].trim().equals("0")) {
String text = content.getText().toString();
SpannableString span = new SpannableString(text);
span.setSpan(new UnderlineSpan(), 0, span.length(), 0);
// content.setText(span);
} else if (tcolor[2].trim().equals("3")) {
// content.setTypeface(null, Typeface.BOLD);
String text = content.getText().toString();
SpannableString span = new SpannableString(text);
span.setSpan(new UnderlineSpan(), 0, span.length(), 0);
// content.setText(span);
} else if (tcolor[2].trim().equals("4")) {
// content.setTypeface(null, Typeface.ITALIC);
String text = content.getText().toString();
SpannableString span = new SpannableString(text);
span.setSpan(new UnderlineSpan(), 0, span.length(), 0);
// content.setText(span);
} else if (tcolor[2].trim().equals("1")) {
// content.setTypeface(null, Typeface.BOLD);
String text = content.getText().toString();
SpannableString span = new SpannableString(text);
span.removeSpan(text);
} else if (tcolor[2].trim().equals("2")) {
// content.setTypeface(null, Typeface.ITALIC);
String text = content.getText().toString();
SpannableString span = new SpannableString(text);
span.removeSpan(text);
} else {
String text = content.getText().toString();
SpannableString span = new SpannableString(text);
span.removeSpan(text);
}
} catch (IndexOutOfBoundsException e) {
// TODO: handle exception
}
grid_layout.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
int i = grid.getCount();
Intent intentAlarm = new Intent(WidgetActivity.this,
WriteNotesActivity.class);
intentAlarm.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP
| Intent.FLAG_ACTIVITY_SINGLE_TOP);
intentAlarm.putExtra("max", s);
startActivity(intentAlarm);
finish();
}
});
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
} catch (Exception e) {
// finish();
}
}
public static Bitmap decodeSampledBitmapFromResource(String resId) {
// First decode with inJustDecodeBounds=true to check dimensions
final BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
BitmapFactory.decodeFile(resId, options);
// Calculate inSampleSize
options.inSampleSize = calculateInSampleSize(options, 400, 300);
// Decode bitmap with inSampleSize set
options.inJustDecodeBounds = false;
return BitmapFactory.decodeFile(resId, options);
}
public static int calculateInSampleSize(BitmapFactory.Options options,
int reqWidth, int reqHeight) {
// Raw height and width of image
final int height = options.outHeight;
final int width = options.outWidth;
int inSampleSize = 1;
if (height > reqHeight || width > reqWidth) {
final int halfHeight = height / 2;
final int halfWidth = width / 2;
// Calculate the largest inSampleSize value that is a power of 2 and
// keeps both
// height and width larger than the requested height and width.
while ((halfHeight / inSampleSize) > reqHeight
|| (halfWidth / inSampleSize) > reqWidth) {
inSampleSize *= 2;
}
}
return inSampleSize;
}
}
This might help someone out there after several hours without an answer to this. I found a way of solving this without using Picasso in handling the outOfMemoryError. I added this line of code in my Manifest file.
android:largeHeap="true"
I added this to the entire application here as below:-
<application
android:icon="#drawable/ic_launcher"
android:largeHeap="true"
android:label="#string/app_name" >
android:largeHeap is the instrument for increasing your allocated memory to app.
EDIT:
well, you are using too much memory. remove those 3 lines of code :
File imgFile = new File(data.get(position).get("path"));
Bitmap myBitmap = BitmapFactory.decodeFile(imgFile.getAbsolutePath());
imageView.setImageBitmap(myBitmap);
simply, you are assigning too much space to these instances and your phone runs out of memory. Just use my response and consider logging the file path so you can possibly use that without creating another file.
i think you used wrong implementation. Probably the context is not adressing correctly and therefore, i would personally use "this" instead. And for loading resources, their guide provides us with three implementations, see below:
pass drawable
Picasso.with(context).load(R.drawable.landing_screen).into(imageView1);
pass uri
Picasso.with(context).load("file:///android_asset/DvpvklR.png").into(imageView2);
pass file
Picasso.with(context).load(new File(...)).into(imageView3);
so therefore i would decode the image using this code:
Picasso.with(this).load(new File(data.get(position).get("path"))).into(imageView);
I have created a screen in which have created RelativeLayout dynamically. After that I have added some ImageView under RelativeLayout.
The requirement is that when I click on any Image View then that ImageView should be zoom by 20% and other images show be adjusted automatically.
So I have two problems:
How to zoom a particular ImageView (other ImagesView should be zoom out if already zoomed in)
How to adjust other Image View when perform zoom in and zoom out
Please suggest, I have not worked on Animation before.
Here is code to create layout dynamically:
// Method for adding layout and images
private void addRow(List<HashMap<String, String>> list) {
int breaker = 4, j, row = 0, tempSize = 0;
// Getting number of rows to create
row = (drinkList.size() % 5) == 0 ? drinkList.size() / 5 : (drinkList.size() / 5) + 1;
// Looping for rows
for (j = 0; j < row; j++) {
// Specifying breaker value to break the images row
if (j % 2 != 0) {
breaker = 4;
} else {
breaker = 5;
}
// Creating layout for rows
RelativeLayout layout = new RelativeLayout(Drinks.this);
layout.setId(111 + j);
// Setting layout parameters to row layout
// layout.setLayoutParams(new
// LayoutParams(LayoutParams.WRAP_CONTENT,
// LayoutParams.WRAP_CONTENT, Gravity.CENTER));
RelativeLayout.LayoutParams newParams = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT,
RelativeLayout.LayoutParams.WRAP_CONTENT);
if (j > 0) {
newParams.addRule(RelativeLayout.BELOW, (111 + j) - 1);
}
layout.setLayoutParams(newParams);
int c = 0;
tempSize = list.size();
// Looping for placing Images
while (tempSize != 0 && c < breaker) {
// getting hash map from list
HashMap<String, String> h = new HashMap<String, String>();
h = list.get(0);
// Creating Image
final ImageView imageView = new ImageView(Drinks.this);
// Layout Parameters for Image
LayoutParams lpImage = new LayoutParams(150, 150);
imageView.setId(111 + c);
if (c > 0) {
lpImage.addRule(RelativeLayout.RIGHT_OF, (111 + c) - 1);
}
imageView.setTag(c);
lpImage.setMargins(10, 10, 10, 10);
imageView.setLayoutParams(lpImage);
URI uri = null;
URL imageUrl;
String brandID, categoryID, flavourID;
try {
imageUrl = new URL(h.get(Utility.KEY_ICON).toString().replace(" ", "%20"));
brandID = h.get(Utility.KEY_BRAND_ID);
categoryID = h.get(Utility.KEY_CATEGORY_ID);
flavourID = h.get(Utility.KEY_FLAVOUR_ID);
// HashMap<String, String> hash = new HashMap<String,
// String>();
// hash.put(Utility.KEY_BRAND_ID, brandID);
// hash.put(Utility.KEY_CATEGORY_ID, categoryID);
// Setting tag
imageView.setTag(brandID);
uri = new URI(imageUrl.toString());
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (URISyntaxException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// Loading image from URLs
ImageLoader imageLoader = new ImageLoader(Drinks.this);
imageLoader.DisplayImage(uri.toString(), R.drawable.ic_launcher, imageView);
/**
* Click Listener of Image
* **/
imageView.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Toast.makeText(Drinks.this, "TAG " + imageView.getTag(), 2000).show();
if (!pressed) {
imageView.startAnimation(zoomIn);
pressed = !pressed;
} else {
imageView.startAnimation(zoomOut);
pressed = !pressed;
}
}
});
layout.addView(imageView);
// removing items from list
list.remove(0);
c++;
tempSize--;
}
containerLayout.addView(layout);
}
public class master extends Activity {
ProgressDialog progressDialog;
EditText tahmini_kelime;
EditText girilen_sayi ;
EditText toplam_harf_sayisi ;
Button tamamdir;
TextView jTextArea1;
Vector vector_all,vect_end,vect,recent_search;
BufferedReader read;
String recent_tahmin_kelime;
boolean bayrak,bayrak2 ;
int column_number ;
InputStreamReader inputreader ;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.master);
column_number=0;
bayrak=true;
toplam_harf_sayisi=(EditText)findViewById(R.id.toplam_harf);
tahmini_kelime=(EditText)findViewById(R.id.tahmini_kelime);
girilen_sayi=(EditText)findViewById(R.id.sayi_gir);
tamamdir=(Button)findViewById(R.id.tamamdirrrr);
jTextArea1=(TextView)findViewById(R.id.jte);
bayrak2=true;
recent_search = new Vector();
InputStream inputStream = getResources().openRawResource(R.raw.sozluk);
try {
inputreader = new InputStreamReader(inputStream,"utf-8");
} catch (UnsupportedEncodingException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
};
read = new BufferedReader(inputreader);
int k = 0;
String result = "";
try {
vector_all = new Vector();
while (read.ready()) {
result = read.readLine();
vector_all.add(result);
jTextArea1.append(result + "\n");
k = k + 1;
}
String size = "" + k;
} catch (IOException ex) {
}
tamamdir.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
if( bayrak2 )
{
if(Integer.parseInt(toplam_harf_sayisi.getText().toString())>8 || Integer.parseInt(toplam_harf_sayisi.getText().toString())<=1)
{
toplam_harf_sayisi.setText("");
Dialog dl=new Dialog(master.this);
dl.setTitle("hatalı giriş");
dl.setCanceledOnTouchOutside(true);
dl.show();
return;
}
int findwordlength = Integer.parseInt(toplam_harf_sayisi.getText().toString());
int k = 0;
String result = "";
jTextArea1.setText("");
InputStream inputStream = getResources().openRawResource(R.raw.sozluk);
try {
inputreader = new InputStreamReader(inputStream,"utf-8");
} catch (UnsupportedEncodingException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
};
read = new BufferedReader(inputreader);
String resultword = "";
try {
vect = new Vector();
while (read.ready()) {
result = read.readLine();
if (result.length() == findwordlength) {
vect.addElement(result);
resultword = resultword + result + "\n";
k = k + 1;
}
jTextArea1.setText("");
}
jTextArea1.append(resultword + "\n");
RandomKelime(vector_all,0 );
} catch (IOException ex) {
}
toplam_harf_sayisi.setEnabled(false);
girilen_sayi.setEnabled(true);
bayrak2=false;
}
else
{
progressDialog = ProgressDialog.show(master.this, "Bir Düşüneyim :D", "lütfen bekleyiniz...");
Thread thread = new Thread(new Runnable() {
public void run() {
mainGuessWord(column_number);
handler.sendEmptyMessage(0);
}
});
thread.start();
girilen_sayi.setText("");
}
}
});
}
private void mainGuessWord(int look) {
int result_int = 0;
String randomword = "";
int randomword2 = 0;
randomword = tahmini_kelime.getText().toString();
result_int = Integer.parseInt(girilen_sayi.getText().toString());
if (result_int == 0) {
mevcut_degil(vect, randomword);
} else {
elemeAgaci(vect, randomword, result_int);
}
}
public void elemeAgaci(Vector vect, String elem, int length) {
String word = elem.toString();
Vector cmp_vect;
cmp_vect = new Vector();
vect_end = new Vector();
int count = 0;
int countword = 0; // toplam word sayısı
int each_word_total = 0; // her kelimede bulunan harf sayısı
jTextArea1.setText("");
String compare = "";
for (int i = 0; i < vect.size(); i++) {
each_word_total = 0;
compare = "";
for (int j = 0; j < word.length(); j++) {
if(!compare.contains(""+word.charAt(j)))
{
for (int k = 0; k < vect.get(i).toString().length(); k++) {
if (vect.get(i).toString().charAt(k) == word.charAt(j)) {
each_word_total++;
}
}
compare=""+compare+word.charAt(j);
}
}
System.out.println("" + vect.get(i) + " => " + each_word_total);
if (length == each_word_total) {
cmp_vect.add(vect.get(i));
jTextArea1.append(vect.get(i) + "\n");
countword++;
}
}
vect.clear();
for (int l = 0; l < cmp_vect.size(); l++) {
vect.add(cmp_vect.get(l));
}
if (countword == 1) {
Dialog dl=new Dialog(master.this);
dl.setTitle("The Word id : "+jTextArea1.getText().toString());
dl.setCanceledOnTouchOutside(true);
dl.show();
} else {
column_number = column_number + 1;
if(vect.size()<10){
RandomKelime_Table(vect);
}else{
RandomKelime(vector_all, column_number);
}
}
}
public void mevcut_degil(Vector vect, String m) {
char control[];
control = m.toCharArray();
boolean flag = false;
int countword = 0;
Vector detect;
detect = new Vector();
jTextArea1.setText("");
for (int k = 0; k < vect.size(); k++) {
flag = false;
for (int s = 0; s < control.length; s++) {
if (vect.get(k).toString().contains("" + control[s])) {
flag = true;
}
}
if (!flag) {
detect.addElement(vect.get(k));
countword = countword + 1;
}
}
vect.clear();
for (int s = 0; s < detect.size(); s++) {
vect.addElement(detect.get(s));
}
for (int a = 0; a < countword; a++) {
jTextArea1.append(vect.get(a).toString() + "\n");
}
if (countword == 1) {
Dialog dl=new Dialog(master.this);
dl.setTitle("The Word id : "+jTextArea1.getText().toString());
dl.setCanceledOnTouchOutside(true);
dl.show();
}
else {
column_number = column_number + 1;
RandomKelime(vect, column_number);
}
}
public void RandomKelime(Vector vector, int k)
{
String sesli[]={"a","e","ı","i","o","ö","u","ü"};
Random a = new Random();
if (k == 0) {
String passedword = "";
passedword = vector_all.get((int) (Math.random() * vector_all.size())).toString();
while (passedword.length() < 8) {
passedword = vector_all.get((int) (Math.random() * vector_all.size())).toString();
}
tahmini_kelime.setText(passedword);
recent_tahmin_kelime=passedword;
// jTable1.setValueAt(vector_all.get((int) (Math.random() * vector_all.size())), k, 0);
} else {
recent_search.addElement(recent_tahmin_kelime );
int say = 0;
String design = "";
String guess_words = "";
String as="";
int f=0;
int count=0;
int calculate_all=0;
for (int u = 0; u < recent_search.size(); u++) {
design = recent_search.get(u).toString();
bayrak = false;
as="";
count=0;
for(int s=0;s<sesli.length;s++)
{
if(design.contains(""+sesli[s]) && count==0){
as+=""+sesli[s];
count++;
}
}
guess_words = vector_all.get((int) a.nextInt(vector_all.size())).toString();
while (guess_words.length() < 8) {
guess_words = vector_all.get((int) (Math.random() * vector_all.size())).toString();
}
while (say < design.length()) {
calculate_all=0;
while (guess_words.contains("" + as) && !design.equals(guess_words)) {
say = 0;
calculate_all++;
guess_words = vector_all.get( a.nextInt(vector_all.size())).toString();
while (guess_words.length() < 8) {
guess_words = vector_all.get((int) (Math.random() * vector_all.size())).toString();
}
f=f+1;
System.out.println("Tahmın: " + guess_words + " => " + design);
if(calculate_all>vect.size())
{
break;
}
}
say++;
System.out.println("coutn: " + say);
}
}
if (true) {
tahmini_kelime.setText(guess_words);
}
}
}
public void RandomKelime_Table(Vector vector ) {
String passedword = "";
Random a = new Random();
try {
passedword = vect.get(a.nextInt(vect.size())).toString();
} catch (Exception e) {
Dialog dl=new Dialog(master.this);
dl.setTitle("Hatalı Giriş.Yeniden Başlayın.");
dl.setCanceledOnTouchOutside(true);
dl.show();
yeniden_basla();
}
tahmini_kelime.setText(passedword );
}
public void yeniden_basla()
{
bayrak2=true;
girilen_sayi.setEnabled(false);
toplam_harf_sayisi.setEnabled(true);
toplam_harf_sayisi.setText("");
vect.clear();
vector_all.clear();
vect_end.clear();
recent_search.clear();
jTextArea1.setText("");
recent_tahmin_kelime="";
column_number=0;
bayrak=true;
InputStream inputStream = getResources().openRawResource(R.raw.sozluk);
try {
inputreader = new InputStreamReader(inputStream,"utf-8");
} catch (UnsupportedEncodingException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
};
read = new BufferedReader(inputreader);
int k = 0;
String result = "";
try {
vector_all = new Vector();
while (read.ready()) {
result = read.readLine();
vector_all.add(result);
jTextArea1.append(result + "\n");
k = k + 1;
}
String size = "" + k;
} catch (IOException ex) {
}
}
private Handler handler = new Handler() {
#Override
public void handleMessage(Message msg) {
progressDialog.dismiss();
}
};
}
this all of my code.
You don't show where you create your handler (onCreate ? onStart ? somewhere else ?). Is it started from the main thread ? If so, you need to be provide a more complete stack trace so we can understand.
If you're starting it from another thread then that's the issue because it's attempting to change progressDialog and that must be done from the main thread.
PS: if you used an AsyncTask you wouldn't have to scratch your head around this as it's designed to do exactly what you want and be thread safe.
Post comment : use an AsyncThread : add the progress bar in onPreExecute(), change run() to doInBackground() and move the dismiss() to onPostExecute(