Error with a boolean method in my app - java

I am developing an app like Logo Quiz ... This is the activity, where you have to write the name of the logo:
public class Vie extends Activity implements OnClickListener {
ImageView img;
EditText et;
Button btn;
TextView txt;
MediaPlayer win_sound, wrong_sound;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.vie);
img = (ImageView) findViewById(R.id.img);
et = (EditText) findViewById(R.id.et);
btn = (Button) findViewById(R.id.btnCheck);
txt = (TextView) findViewById(R.id.txt);
win_sound = MediaPlayer.create(Vie.this, R.raw.win);
wrong_sound= MediaPlayer.create(Vie.this, R.raw.wrong);
setImageAndTagByIntent(img);
btn.setOnClickListener(this);
}
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
boolean mb = check(et, img);
Intent i = getIntent();
if (mb) {
// Sunet toast thread
txt.setText(title(img));
win_sound.start();
i.putExtra("score", "1");
setResult(RESULT_OK, i);
Thread t = new Thread() {
#Override
public void run() {
// TODO Auto-generated method stub
super.run();
try {
sleep(win_sound.getDuration());
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
} finally {
finish();
}
}
};
t.start();
}
if (!mb) {
// sunet toast thread
wrong_sound.start();
Toast t = Toast.makeText(getApplicationContext(),"Wrong answer! Please check if you have spelled corectly the name of the team!",Toast.LENGTH_LONG);
t.show();
}
}
private String title(ImageView img2) {
// TODO Auto-generated method stub
String s = (String) img2.getTag();
return s;
}
private void setImageAndTagByIntent(ImageView img2) {
// TODO Auto-generated method stub
// Trece si tagul!
Intent i = getIntent();
Bitmap back = i.getParcelableExtra("back");
Drawable b = new BitmapDrawable(getResources(), back);
img2.setImageDrawable(b);
String tag = i.getStringExtra("tag");
Object tag2 = (Object) tag;
img2.setTag(tag2);
}
private boolean check(EditText et2, ImageView img2) {
// TODO Auto-generated method stub
String s = et2.getText().toString();
s = WordUtils.capitalize(s);
String s1 = (String) img2.getTag();
boolean b;
if ((s1.contains("") && s.contentEquals(firstWord(s1)))||(s.contentEquals(s1) && !s1.contains(""))) {
b = true;
}else {
b=false;
}
return b;
}
private String firstWord(String s1) {
// TODO Auto-generated method stub
String arr[] = s1.split("//s");
return arr[0];
}
}
It works ... but when the name of the logo has two words and when I put only the first word, it says that it is wrong! It works only with the full name. Please Help Me!

Change the below condition:
private String firstWord(String s1) {
// TODO Auto-generated method stub
String arr[] = s1.split(" ");
return arr[0];
}
Also change your if condition:
((s1.contains(" ") && s.contentEquals(firstWord(s1)))||(s.contentEquals(s1) && !s1.contains(" ")))

I think it's a problem with your firstWord function. Try changing it to:
private String firstWord(String s1) {
String arr[] = s1.split(" ");
return arr[0];
}
Also, change this:
if ((s1.contains("") && s.contentEquals(firstWord(s1)))||(s.contentEquals(s1) && !s1.contains("")))
To:
if ((s1.contains(" ") && s.contentEquals(firstWord(s1)))||(s.contentEquals(s1) && !s1.contains(" ")))

Related

How to populate my Spinner based on the value on my TextView?

I am new to Android programming and I'm working on a project that fetches data from MySQL DB.
Now, I have two java files. The first fetches employees and their id, it has Spinners that when clicked, it copies the value of the name and id of the employees to the TextViews and transfer the data to the next Activity through Intent.
While the second fetches employees' schedule based on the employee id. This second activity should populate Spinner based on the id of the employees that was passes from the first activity.
First Activity:
public class FirstActivity extends Activity {
JSONObject jObj;
JSONArray jArray;
ProgressDialog pd;
ArrayList < String > aestheticianList;
ArrayList < Items > items;
Button btnTransact;
String service_name, price;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.spinner_farmers_aesthetician);
new DownloadJSON().execute();
btnTransact = (Button) findViewById(R.id.btnTransact);
btnTransact.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent i = new Intent(cp000l3.flawlessfaceandbodyclinic.project.transact.FarmersAestheticianActivity.this,
cp000l3.flawlessfaceandbodyclinic.project.transact.FarmersDateTimeActivity.class);
String service_name = ((TextView) findViewById(R.id.service_name)).getText().toString();
String price = ((TextView) findViewById(R.id.price)).getText().toString();
String full_name = ((TextView) findViewById(R.id.full_name)).getText().toString();
String aid = ((TextView) findViewById(R.id.aid)).getText().toString();
i.putExtra("service_name", service_name);
i.putExtra("price", price);
i.putExtra("full_name", full_name);
i.putExtra("aid", aid);
startActivityForResult(i, 100);
}
});
TextView txtService_name = (TextView) findViewById(R.id.service_name);
TextView txtPrice = (TextView) findViewById(R.id.price);
Intent i = getIntent();
service_name = i.getStringExtra("service_name");
price = i.getStringExtra("price");
txtService_name.setText(service_name);
txtPrice.setText(price);
}
private class DownloadJSON extends AsyncTask < Void, Void, Void > {
#Override
protected Void doInBackground(Void...params) {
// TODO Auto-generated method stub
items = new ArrayList < Items > ();
aestheticianList = new ArrayList < String > ();
try {
jObj = JSONParser.getJSONfromURL("http://192.168.1.9:8013/flawlessadmin/storescripts/transaction/final/get_aesthetician2.php");
try {
jArray = jObj.getJSONArray("aesthetician");
for (int i = 0; i < jArray.length(); i++) {
jObj = jArray.getJSONObject(i);
Items item = new Items();
item.setFull_name(jObj.optString("full_name"));
item.setAid(jObj.optString("aid"));
items.add(item);
aestheticianList.add(jObj.optString("full_name"));
}
} catch (Exception e) {
Log.e("Error", e.getMessage());
e.printStackTrace();
}
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
protected void onPostExecute(Void args) {
Spinner spin = (Spinner) findViewById(R.id.spin_aesthetician);
spin.setAdapter(new ArrayAdapter < String > (FarmersAestheticianActivity.this,
android.R.layout.simple_spinner_dropdown_item, aestheticianList));
spin.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView <? > arg0, View arg1,
int position, long arg3) {
// TODO Auto-generated method stub
TextView txt_full_name = (TextView) findViewById(R.id.full_name);
TextView txt_aid = (TextView) findViewById(R.id.aid);
txt_full_name.setText(items.get(position).getFull_name());
txt_aid.setText(items.get(position).getAid());
////////////////////////////////
////////////////////////////////
}
#Override
public void onNothingSelected(AdapterView <? > parent) {
// TODO Auto-generated method stub
}
});
}
}
}
Second Activity:
public class SecondActivity extends Activity {
JSONObject jObj;
JSONArray jArray;
ProgressDialog pd;
ArrayList < String > dateTimeList;
ArrayList < Items > items;
Button btnTransact;
String service_name, price, full_name, aid, tid;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.spinner_farmers_datetime);
new DownService().execute();
btnTransact = (Button) findViewById(R.id.btnTransact);
btnTransact.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent i = new Intent(cp000l3.flawlessfaceandbodyclinic.project.transact.FarmersDateTimeActivity.this,
cp000l3.flawlessfaceandbodyclinic.project.transact.FarmersConfirmationActivity.class);
String service_name = ((TextView) findViewById(R.id.service_name)).getText().toString();
String price = ((TextView) findViewById(R.id.price)).getText().toString();
String aid = ((TextView) findViewById(R.id.aid)).getText().toString();
String full_name = ((TextView) findViewById(R.id.full_name)).getText().toString();
String tid = ((TextView) findViewById(R.id.tid)).getText().toString();
String datetime = ((TextView) findViewById(R.id.datetime)).getText().toString();
i.putExtra("service_name", service_name);
i.putExtra("price", price);
i.putExtra("aid", aid);
i.putExtra("full_name", full_name);
i.putExtra("tid", tid);
i.putExtra("date_time", datetime);
startActivityForResult(i, 100);
}
});
TextView txtService_name = (TextView) findViewById(R.id.service_name);
TextView txtPrice = (TextView) findViewById(R.id.price);
TextView txtFull_name = (TextView) findViewById(R.id.full_name);
TextView txtAid = (TextView) findViewById(R.id.aid);
Intent i = getIntent();
service_name = i.getStringExtra("service_name");
price = i.getStringExtra("price");
full_name = i.getStringExtra("full_name");
aid = i.getStringExtra("aid");
txtService_name.setText(service_name);
txtPrice.setText(price);
txtFull_name.setText(full_name);
txtAid.setText(aid);
}
private class DownService extends AsyncTask < Void, Void, Void > {
#Override
protected Void doInBackground(Void...params) {
// TODO Auto-generated method stub
items = new ArrayList < Items > ();
dateTimeList = new ArrayList < String > ();
/////////////////////////
List < NameValuePair > param = new ArrayList < NameValuePair > ();
param.add(new BasicNameValuePair("aid", aid));
/////////////////////////
try {
String jObj = JSONParser.makeHttpRequest2("http://192.168.1.9:8013/flawlessadmin/storescripts/transaction/final/get_time2.php", "GET", param); //("http://192.168.1.9:8013/flawlessadmin/storescripts/transaction/final/get_time.php");
try {
JSONObject jsonObj = new JSONObject(jObj);
for (int i = 0; i < jArray.length(); i++) {
jsonObj = jArray.getJSONObject(i);
Items item = new Items();
item.setDateTime(jsonObj.optString("date_time"));
item.setTid(jsonObj.optString("tid"));
items.add(item);
dateTimeList.add(jsonObj.optString("date_time"));
}
} catch (Exception e) {
Log.e("Error", e.getMessage());
e.printStackTrace();
}
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
protected void onPostExecute(Void args) {
Spinner spin = (Spinner) findViewById(R.id.spin_datetime);
spin.setAdapter(new ArrayAdapter < String > (FarmersDateTimeActivity.this,
android.R.layout.simple_spinner_dropdown_item, dateTimeList));
spin.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView <? > arg0, View arg1,
int position, long arg3) {
// TODO Auto-generated method stub
TextView txt_datetime = (TextView) findViewById(R.id.datetime);
TextView txt_tid = (TextView) findViewById(R.id.tid);
txt_datetime.setText(items.get(position).getDateTime());
txt_tid.setText(items.get(position).getTid());
////////////////////////////////
////////////////////////////////
}
#Override
public void onNothingSelected(AdapterView <? > parent) {
// TODO Auto-generated method stub
}
});
}
}
}
in second Activity:
Bundle extras = getIntent().getExtras();
int id = extras.getInt("Id"); // get the id passed from first activty

How select inbox msg by default display on spinner

In the system when I select msg that msg by default display on spinner.I require this project those select item display only spinner.If I change item not show previous select item display on spinner.
list.java
Spinner sp1;
TextView entry;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.list);
sp1=(Spinner) findViewById(R.id.spinner1);
entry = (TextView)findViewById(R.id.TextView123);
getFilesnames();
}
private void getFilesnames() {
// TODO Auto-generated method stub
String[] filenames=getApplicationContext().fileList();
List<String> list=new ArrayList<String>();
for(int i=0;i<filenames.length;i++){
list.add(filenames[i]);
}
ArrayAdapter<String> filenameAdapter=new ArrayAdapter<String>(this,android.R.layout.simple_spinner_item,list);
sp1.setAdapter(filenameAdapter);
}
public void onClick(View v) {
// TODO Auto-generated method stub
String selectFile = String.valueOf(sp1.getSelectedItem());
openFile(selectFile);
}
private void openFile(String selectFile) {
// TODO Auto-generated method stub
String value = "";
FileInputStream fis;
try {
fis = openFileInput(selectFile);
byte[] input = new byte[fis.available()];
while(fis.read(input) != -1){
value += new String(input);
}
fis.close();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
entry.setText(value);
}
Check whether list has value after binding like following code:
private void getFilesnames() {
// TODO Auto-generated method stub
String[] filenames=getApplicationContext().fileList();
List<String> list=new ArrayList<String>();
for(int i=0;i<filenames.length;i++){
list.add(filenames[i]);
}
/***
check here list has value or not
***/
if(list.size() <= 0) {
list.add("You string.....");
}
ArrayAdapter<String> filenameAdapter=new ArrayAdapter<String>(this,android.R.layout.simple_spinner_item,list);
sp1.setAdapter(filenameAdapter);
}

An error connecting to Android Spinner

I am working on an Android app where I have a Spinner, and on the base of which item I choose, the app will read in text file number 1 or number 2, etc... I have written a code, but when I run it on my device, it says that "The application has stopped unexpectedly".
Here is my code:
public class MainActivity extends Activity implements OnClickListener, OnItemSelectedListener {
Spinner spinner;
String textSource = "";
TextView textMsg;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textMsg = (TextView) findViewById(R.id.textmsg);
spinner=(Spinner) findViewById(R.id.spinner1);
List<String> list = new ArrayList<String>();
list.add("list 1");
list.add("list 2");
list.add("list 3");
ArrayAdapter<String> adapter=new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item,list);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner.setAdapter(adapter);
spinner.setOnItemSelectedListener(this);
URL textUrl;
String stringText = "";
try {
textUrl = new URL(textSource);
BufferedReader bufferReader = new BufferedReader(
new InputStreamReader(textUrl.openStream(), "ISO-8859-1"));
//ISO-8859-1
String StringBuffer;
//String stringText = "";
while ((StringBuffer = bufferReader.readLine()) != null) {
stringText += StringBuffer;
}
bufferReader.close();
textMsg.setText(stringText);
//textMsg.setText(string123);
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
textMsg.setText(e.toString());
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
textMsg.setText(e.toString());
}
}
#Override
public void onItemSelected(AdapterView<?> parent, View arg1, int pos,
long arg3) {
// TODO Auto-generated method stub
String Text = parent.getSelectedItem().toString();
if(Text.equals("list 1")) {
textSource = "path/to/textfile 1";
}
else if(Text.equals("list 2")){
textSource = "path/to/textfile 2";
}
else {
}
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
}
How should I solve this problem?
Thanks for helping
I would suggest you to use
String Text = spinner.getSelectedItem().toString();
instead of
String Text = parent.getSelectedItem().toString();
So that it becomes :
#Override
public void onItemSelected(AdapterView<?> parent, View arg1, int pos,
long arg3) {
String Text = spinner.getSelectedItem().toString();
if(Text.equals("list 1")) {
textSource = "path/to/textfile 1";
}
else if(Text.equals("list 2")){
textSource = "path/to/textfile 2";
}
else {
}
// then put your URL code here as follows
URL textUrl;
String stringText = "";
try {
textUrl = new URL(textSource);
BufferedReader bufferReader = new BufferedReader(
new InputStreamReader(textUrl.openStream(), "ISO-8859-1"));
//ISO-8859-1
String StringBuffer;
while ((StringBuffer = bufferReader.readLine()) != null) {
stringText += StringBuffer;
}
bufferReader.close();
textMsg.setText(stringText);
//textMsg.setText(string123);
} catch (MalformedURLException e) {
e.printStackTrace();
textMsg.setText(e.toString());
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
textMsg.setText(e.toString());
}
}
Since you are calling textUrl = new URL(textSource); inside oncreate() method textSource will be always " ". Better create a method and pass the new textSource value based on onItemSelected .
Sample for Your reference: By Default Link1 will be passed
#Override
public void onItemSelected(AdapterView<?> parent, View arg1, int pos,
long arg3) {
String Text = parent.getSelectedItem().toString();
if (Text.equals("list 1")) {
Method("path/to/textfile 1");
} else if (Text.equals("list 2")) {
Method("path/to/textfile 2");
} else {
}
// TODO Auto-generated method stub
}
Method :
public void Method(String textSource) {
URL textUrl;
String stringText = "";
try {
textUrl = new URL(textSource);
BufferedReader bufferReader = new BufferedReader(
new InputStreamReader(textUrl.openStream(), "ISO-8859-1"));
// ISO-8859-1
String StringBuffer;
// String stringText = "";
while ((StringBuffer = bufferReader.readLine()) != null) {
stringText += StringBuffer;
}
bufferReader.close();
textMsg.setText(stringText);
// textMsg.setText(string123);
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
textMsg.setText(e.toString());
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
textMsg.setText(e.toString());
}
}

How to use TextWatcher to automatically get values from edittext and multiply them?

The app force shuts when i enter a number in edittext. I want the app to automatically calculate the BMI when values are entered without pressing on a button.
I know nothing about TextWatcher yet i researched and came up with this code. Its not working though. Whats wrong with it?
public class BodyMassIndex extends Activity implements View.OnClickListener,
TextWatcher {
double result;
EditText age, height, weight;
ToggleButton sex, cmin, kglb;
TextView tvResult;
double heightInt = 1;
double weightInt = 0;
int ageInt;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.bmi);
initialize();
sex.setOnClickListener(this);
cmin.setOnClickListener(this);
kglb.setOnClickListener(this);
}
private void initialize() {
// TODO Auto-generated method stub
age = (EditText) findViewById(R.id.etAge);
height = (EditText) findViewById(R.id.etHeight);
weight = (EditText) findViewById(R.id.etWeight);
sex = (ToggleButton) findViewById(R.id.tbSex);
cmin = (ToggleButton) findViewById(R.id.tbCMIN);
kglb = (ToggleButton) findViewById(R.id.tbKGLB);
tvResult = (TextView) findViewById(R.id.tvResult);
age.addTextChangedListener(this);
height.addTextChangedListener(this);
weight.addTextChangedListener(this);
}
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
switch (v.getId()) {
case R.id.tbCMIN:
heightInt = heightInt * 0.0254;
break;
case R.id.tbKGLB:
weightInt = weightInt * 0.45359237;
break;
}
}
#Override
public void afterTextChanged(Editable s) {
// TODO Auto-generated method stub
calculate();
}
private void calculate() {
// TODO Auto-generated method stub
Editable H = height.getText(), W = weight.getText();
if(H != null)
heightInt = Double.parseDouble(H.toString());
if (W != null)
weightInt = Double.parseDouble(W.toString());
result = weightInt / (heightInt * heightInt);
String textResult = "Your BMI is " + result;
tvResult.setText(textResult);
}
#Override
public void beforeTextChanged(CharSequence s, int start, int count,
int after) {
// TODO Auto-generated method stub
}
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
// TODO Auto-generated method stub
}
}
'
From http://developer.android.com/reference/android/text/TextWatcher.html about afterTextChanged method: "but be careful not to get yourself into an infinite loop, because any changes you make will cause this method to be called again recursively....you can use setSpan(Object, int, int, int) in onTextChanged(CharSequence, int, int, int) "
you already have :
height = (EditText) findViewById(R.id.etHeight);
weight = (EditText) findViewById(R.id.etWeight);
only change calculate() method:
private void calculate()
{
//remove the Editable thing declaration...
heightInt = Double.parseDouble(height.getText().toString());
wightInt = Double.parseDouble(weight.getText().toString());
result = weightInt / (heightInt * heightInt);
String textResult = "Your BMI is " + result;
tvResult.setText(textResult);
}
P.S: Here we're assuming that EditText contains only a number and not letters. Letters will force close the app. So you'll have to check for that.

achartengine : how to repaint / redraw chart

i want to repaint my chart everytime i choose one of m adapter, The first time is the graph is drawn looks perfect, but when I go to the choose one and come back looks like it draws two times the same graph.
this is my source code :
public class MainActivity extends Activity {
private Button btnConnect;
private Spinner spnTime;
private String[] durationData = new String[]{
"Pilih Durasi",
"1 Minggu",
"1 Bulan",
"3 Bulan",
"9 Bulan",
"12 Bulan"
};
int period = 0;
private LinearLayout lnChart;
private ProgressDialog dialog;
public String baseURL = "http://www.abcj.com/i=";
private ArrayList<DataItem> listData;
//CHART VARIABLES
public static final String TYPE = "type";
private XYMultipleSeriesDataset mDataset = new XYMultipleSeriesDataset();
private XYMultipleSeriesRenderer mRenderer = new XYMultipleSeriesRenderer();
private XYSeries mCurrentSeries;
private XYSeriesRenderer mCurrentRenderer;
private String mDateFormat;
private GraphicalView mChartView;
private int index = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btnConnect = (Button)findViewById(R.id.btnDownloadChartData);
spnTime = (Spinner)findViewById(R.id.spOptDuration);
listData = new ArrayList<DataItem>();
//CHART INITIATION
mRenderer.setApplyBackgroundColor(true);
mRenderer.setBackgroundColor(Color.argb(100, 50, 50, 50));
mRenderer.setAxisTitleTextSize(16);
mRenderer.setChartTitleTextSize(20);
mRenderer.setLabelsTextSize(15);
mRenderer.setLegendTextSize(15);
mRenderer.setMargins(new int[] { 20, 30, 15, 0 });
mRenderer.setZoomButtonsVisible(true);
mRenderer.setPointSize(10);
btnConnect.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
ArrayAdapter<String> adapter = new ArrayAdapter<String>(MainActivity.this,
android.R.layout.simple_dropdown_item_1line, durationData);
spnTime.setAdapter(adapter);
spnTime.setOnItemSelectedListener(new OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> arg0, View arg1,
int arg2, long arg3) {
// TODO Auto-generated method stub
switch (arg2+1) {
case 0:
break;
case 1:
period = 7;
break;
case 2:
period = 30;
break;
case 3:
period = 90;
break;
case 4:
period = 180;
break;
case 5:
period = 360;
break;
default:
break;
}
new LoadData(baseURL+period).execute();
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
});
}
});
}
#SuppressLint("ShowToast")
#Override
protected void onResume() {
// TODO Auto-generated method stub
super.onResume();
if (mChartView == null) {
lnChart = (LinearLayout) findViewById(R.id.chart);
mChartView = ChartFactory.getLineChartView(this, mDataset, mRenderer);
mRenderer.setClickEnabled(true);
mRenderer.setSelectableBuffer(100);
mChartView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
SeriesSelection seriesSelection = mChartView.getCurrentSeriesAndPoint();
double[] xy = mChartView.toRealPoint(0);
if (seriesSelection == null) {
Toast.makeText(MainActivity.this, "No chart element was clicked", Toast.LENGTH_SHORT)
.show();
}
}
});
mChartView.setOnLongClickListener(new View.OnLongClickListener() {
#SuppressLint("ShowToast")
#Override
public boolean onLongClick(View v) {
SeriesSelection seriesSelection = mChartView.getCurrentSeriesAndPoint();
if (seriesSelection == null) {
Toast.makeText(MainActivity.this, "No chart element was long pressed",
Toast.LENGTH_SHORT);
return false; // no chart element was long pressed, so let something
// else handle the event
} else {
Toast.makeText(MainActivity.this, "Chart element in series index "
+ seriesSelection.getSeriesIndex() + " data point index "
+ seriesSelection.getPointIndex() + " was long pressed", Toast.LENGTH_SHORT);
return true; // the element was long pressed - the event has been
// handled
}
}
});
mChartView.addZoomListener(new ZoomListener() {
public void zoomApplied(ZoomEvent e) {
String type = "out";
if (e.isZoomIn()) {
type = "in";
}
System.out.println("Zoom " + type + " rate " + e.getZoomRate());
}
public void zoomReset() {
System.out.println("Reset");
}
}, true, true);
mChartView.addPanListener(new PanListener() {
public void panApplied() {
System.out.println("New X range=[" + mRenderer.getXAxisMin() + ", " + mRenderer.getXAxisMax()
+ "], Y range=[" + mRenderer.getYAxisMax() + ", " + mRenderer.getYAxisMax() + "]");
}
});
lnChart.removeAllViews();
lnChart.addView(mChartView, new LayoutParams(LayoutParams.FILL_PARENT,
LayoutParams.FILL_PARENT));
} else {
mChartView.repaint();
}
}
private class LoadData extends AsyncTask<Void, Void, String>{
String url = "";
public LoadData(String url) {
// TODO Auto-generated constructor stub
this.url = url;
}
#Override
protected void onPreExecute() {
// TODO Auto-generated method stub
super.onPreExecute();
dialog = ProgressDialog.show(MainActivity.this, "", "Please wait");
}
#Override
protected String doInBackground(Void... params) {
// TODO Auto-generated method stub
String result = "";
try {
result = Connection.get(url);
} catch (Exception e) {
// TODO: handle exception
result = "";
Log.d("TEST CHART", e.getMessage());
}
return result;
}
#Override
protected void onPostExecute(String result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
fetchResponse(result.replace("\n", "").trim());
dialog.dismiss();
}
}
private void fetchResponse(String result) {
// TODO Auto-generated method stub
if (!result.equals("")) {
try {
JSONArray jsonArray = new JSONArray(result);
DataItem item = null;
for (int i = 1; i < jsonArray.length(); i++) {
JSONObject jsonObject = jsonArray.getJSONObject(i);
item = new DataItem(jsonObject.optString("lji_invest"),
jsonObject.optDouble("persen_hmin1"),
jsonObject.optDouble("lnu_nilai"),
jsonObject.optDouble("selisih"),
jsonObject.optString("lji_id"),
jsonObject.optString("tanggal"));
listData.add(item);
}
renderChart(listData);
} catch (Exception e) {
Log.d("TEST CHART", e.getMessage());
}
}
}
private void renderChart(ArrayList<DataItem> listData) {
// TODO Auto-generated method stub
String seriesTitle = "Series Data";
XYSeries series = new XYSeries(seriesTitle);
mDataset.addSeries(series);
mCurrentSeries = series;
XYSeriesRenderer renderer = new XYSeriesRenderer();
mRenderer.addSeriesRenderer(renderer);
renderer.setFillPoints(true);
mCurrentRenderer = renderer;
for (int i = 0; i < listData.size(); i++) {
mCurrentSeries.add(listData.get(i).getInuNilai(),
listData.get(i).getPersenHmint1());
}
if (mChartView != null) {
mChartView.repaint();
}
}
#Override
protected void onRestoreInstanceState(Bundle savedState) {
super.onRestoreInstanceState(savedState);
mDataset = (XYMultipleSeriesDataset) savedState.getSerializable("dataset");
mRenderer = (XYMultipleSeriesRenderer) savedState.getSerializable("renderer");
mCurrentSeries = (XYSeries) savedState.getSerializable("current_series");
mCurrentRenderer = (XYSeriesRenderer) savedState.getSerializable("current_renderer");
mDateFormat = savedState.getString("date_format");
}
#Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putSerializable("dataset", mDataset);
outState.putSerializable("renderer", mRenderer);
outState.putSerializable("current_series", mCurrentSeries);
outState.putSerializable("current_renderer", mCurrentRenderer);
outState.putString("date_format", mDateFormat);
}
so how to repaint my chart? i hope somebody can show me where is my fault, and tell me the way to fix it
Use chartView.removeView(Graphical_View)
before setting the chart view with new values, followed by use the 'Graphical_View.repaint()' inorder to set new value to the layout
However use multirenderer.setInScroll(true);
Hard to understand the question, but I will try to guess.
In order to repaint the chart, you need to call chartView.repaint();
However, the issue you have may be fixed by having an mRenderer.setInScroll(true); call.
I slove this problem using this code
if(layout != null)
layout.removeAllViews();
layout.addView(mChartView, new LayoutParams(LayoutParams.WRAP_CONTENT,LayoutParams.WRAP_CONTENT));
mChartView = null;

Categories

Resources