when i can call this method on different different situation the graph will be plotted, but the problem is that it overlap the previous one. I have tried lot to clear the previous graph but not able to do that. please any one help me to achieve the same.
As I have attach the screenshot also with the entire code in this, on the click of button from date section i want to plot the graph for that particular date.
but you can see in the attached imaged the data will be overlap on previous one only.
thnks.
//imports here
public class NutrientDailyTrackerActivity extends Fragment {
private static int[] COLORS = new int[] { Color.parseColor("#4CC1D2"),Color.parseColor("#FE2E2E"), Color.parseColor("#298A08") };*
private static String[] NAME_LIST = new String[] { "Fat", "Carbs", "Protein"};
private CategorySeries mSeries = new CategorySeries("");
private DefaultRenderer mRenderer = new DefaultRenderer();
private GraphicalView mChartView;
private String formattedDate;
private TextView currentDate;
private ImageView prevMonth;
private ImageView nextMonth;
private TextView dailyfat;
private TextView dailycarbs;
private String checkingdate;
Calendar c;
Calendar d;
SimpleDateFormat df;
Date date1;
Date date2;
DatabaseHandler db ;
private String uniquecaloriestring ;
private String uniquefat;
private String uniquecarbohydrate ;
private String uniqueprotein;
LinearLayout layout=null;
private static final String DATABASE_NAME = "ndietguru.db";
private double ddcalorie ;
private double ddcalorieconsumed ;
private double ddcalorieburned ;
private double ddfatgoal ;
private double ddproteingoal ;
private double ddcarbohydrategoal;
private double dFat;
private double dCarbs;
private double dProteins;
private double dunical ;
private double dunifat ;
private double dunicarbs ;
private double duniprotein;
private int dbtotalfat;
private int dbtotalcarbs;
private int dbtotalproteins;
private int dbcalorie;
private int dbcalorieburned;
View rootView=null;
private double calorie;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
rootView = inflater.inflate(R.layout.activity_nutrient_details, container, false);
currentDate = (TextView)rootView.findViewById(R.id.currentMonth);
prevMonth = (ImageView)rootView.findViewById(R.id.prevMonth);
nextMonth = (ImageView)rootView.findViewById(R.id.nextMonth);
db = new DatabaseHandler(getActivity());
HashMap<String, String> user = new HashMap<String, String>();
user = db.getUserCalDetails();
uniquefat = (String) user.get("fat");
uniquecarbohydrate = (String) user.get("carbohydrate");
uniqueprotein = (String) user.get("protein");
if(formattedDate == null){
c = Calendar.getInstance();
df = new SimpleDateFormat("yyyy-MM-dd",java.util.Locale.getDefault());
formattedDate = df.format(c.getTime());
try {
date1 = df.parse(formattedDate);
c.setTime(date1);
} catch (ParseException e) {
e.printStackTrace();
}
}
else{
System.out.println("date in fragment" + formattedDate);
c = Calendar.getInstance();
df = new SimpleDateFormat("yyyy-MM-dd",java.util.Locale.getDefault());
System.out.println("inside else");
try {
date1 = df.parse(formattedDate);
c.setTime(date1);
} catch (ParseException e) {
e.printStackTrace();
}
}
//calendar for checking date
d = Calendar.getInstance();
checkingdate = df.format(d.getTime());
try {
date2 = df.parse(checkingdate);
d.setTime(date2);
} catch (ParseException e) {
e.printStackTrace();
}
if(date1.equals(date2))
{
nextMonth.setVisibility(View.GONE);
}
else
{
nextMonth.setVisibility(View.VISIBLE);
}
selectdata();
dbtotalfat = Math.round(dbtotalfat);
dbtotalcarbs = Math.round(dbtotalcarbs);
dbtotalproteins = Math.round(dbtotalproteins);
int[] VALUES = new int[] {dbtotalfat, dbtotalcarbs, dbtotalproteins };
currentDate.setText(formattedDate);
drawGraph(VALUES);
prevMonth.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
c.add(Calendar.DATE, -1);
formattedDate = df.format(c.getTime());
currentDate.setText(formattedDate);
d = Calendar.getInstance();
checkingdate = df.format(d.getTime());
if(formattedDate.equals(checkingdate))
{
nextMonth.setVisibility(View.GONE);
}
else
{
nextMonth.setVisibility(View.VISIBLE);
}
selectprevdata();
dbtotalfat = Math.round(dbtotalfat);
dbtotalcarbs = Math.round(dbtotalcarbs);
dbtotalproteins = Math.round(dbtotalproteins);
System.out.println("on prev fat"+dbtotalfat);
System.out.println("on prev carbs"+dbtotalcarbs);
System.out.println("on prev Pro"+dbtotalproteins);
int[] VALUES = new int[] {dbtotalfat, dbtotalcarbs, dbtotalproteins };
currentDate.setText(formattedDate);
drawGraph(VALUES);
System.out.println("From outside Block");
System.out.println("This is formated date"+formattedDate);
}
});
//Next Button For Date
nextMonth.setOnClickListener(new OnClickListener() {
#Override public void onClick(View v){
c.add(Calendar.DATE, 1);
formattedDate = df.format(c.getTime());
currentDate.setText(formattedDate);
final Calendar d = Calendar.getInstance();
checkingdate = df.format(d.getTime());
if(formattedDate.equals(checkingdate))
{
nextMonth.setVisibility(View.GONE);
}
else
{
nextMonth.setVisibility(View.VISIBLE);
}
selectnextdata();
dbtotalfat = Math.round(dbtotalfat);
dbtotalcarbs = Math.round(dbtotalcarbs);
dbtotalproteins = Math.round(dbtotalproteins);
int[] VALUES = new int[] {dbtotalfat, dbtotalcarbs, dbtotalproteins };
currentDate.setText(formattedDate);
drawGraph(VALUES);
}
});
return rootView;
}
private void selectdata() {
DatabaseHandler helper = new DatabaseHandler(getActivity());
SQLiteDatabase db = helper.getReadableDatabase();
String calorieConsumedQuery = "SELECT SUM(calorie) AS dbcalorie,SUM(fat) AS dbtotalfat,SUM(carbohydrate) AS dbtotalcarbs,SUM(protein)AS Totalprotein FROM Meal WHERE createddate = ('"+formattedDate+"')";
String caloriBurnedQuery = "SELECT SUM(calorieburned) AS dbcalorieburned FROM ExerciseData WHERE createddate = ('"+formattedDate+"')";
String calorieDetailsQuery = "SELECT caloriegoal, calorieconsumed,calorieburned, fatgoal, proteingoal,carbohydrategoal FROM dailyDetails WHERE createddate = (SELECT MAX(createddate) FROM dailyDetails WHERE createddate <= ('"+formattedDate+"'))";
Cursor calorieConsumedQueryCursor = db.rawQuery(calorieConsumedQuery,null);
Cursor calorieBurnedQueryCursor = db.rawQuery(caloriBurnedQuery,null);
Cursor calorieDetailsQueryCursor = db.rawQuery(calorieDetailsQuery,null);
if (!calorieConsumedQueryCursor.isAfterLast()) {
calorieConsumedQueryCursor.moveToFirst();
while (!calorieConsumedQueryCursor.isAfterLast()) {
dbcalorie= (int) Math.round(calorieConsumedQueryCursor.getDouble(0));
dbtotalfat = (int) Math.round(calorieConsumedQueryCursor.getDouble(1));
dbtotalcarbs = (int) Math.round(calorieConsumedQueryCursor.getDouble(2));
dbtotalproteins = (int) Math.round(calorieConsumedQueryCursor.getDouble(3));
calorieConsumedQueryCursor.moveToNext();
}
}
if (!calorieBurnedQueryCursor.isAfterLast()) {
calorieBurnedQueryCursor.moveToFirst();
while (!calorieBurnedQueryCursor.isAfterLast()) {
dbcalorieburned = (int) Math.round(calorieBurnedQueryCursor.getDouble(0));
Log.e("calorie info"," dbcalorieburned: " + dbcalorieburned);
calorieBurnedQueryCursor.moveToNext();
}
}
if (!calorieDetailsQueryCursor.isAfterLast()) {
calorieDetailsQueryCursor.moveToFirst();
while (!calorieDetailsQueryCursor.isAfterLast()) {
calorie = (int) Math.round(calorieDetailsQueryCursor.getDouble(0));
ddcalorieconsumed = (int) Math.round(calorieDetailsQueryCursor.getDouble(1));
ddcalorieburned = (int) Math.round(calorieDetailsQueryCursor.getDouble(2));
dFat = (int) Math.round(calorieDetailsQueryCursor.getDouble(3));
dProteins = (int) Math.round(calorieDetailsQueryCursor.getDouble(4));
dCarbs = (int) Math.round(calorieDetailsQueryCursor.getDouble(5));
Log.e("Daily info"," ddcalorie: " + calorie);
Log.e("Daily info"," ddcalorieconsumed: " + ddcalorieconsumed);
Log.e("Daily info"," ddcalorieburned: " + ddcalorieburned);
Log.e("Daily info"," ddfatgoal: " + dFat);
Log.e("Daily info"," ddproteingoal: " + dProteins);
Log.e("Daily info"," ddcarbohydrategoal: " + dCarbs);
calorieDetailsQueryCursor.moveToNext();
}
}
calorieConsumedQueryCursor.close();
calorieBurnedQueryCursor.close();
calorieDetailsQueryCursor.close();
db.close();
}
private void selectprevdata() {
DatabaseHandler helper = new DatabaseHandler(getActivity());
SQLiteDatabase db = helper.getReadableDatabase();
String calorieConsumedQuery = "SELECT SUM(calorie) AS dbcalorie,SUM(fat) AS dbtotalfat,SUM(carbohydrate) AS dbtotalcarbs,SUM(protein)AS Totalprotein FROM Meal WHERE createddate = ('"+formattedDate+"')";
String caloriBurnedQuery = "SELECT SUM(calorieburned) AS dbcalorieburned FROM ExerciseData WHERE createddate = ('"+formattedDate+"')";
String calorieDetailsQuery = "SELECT caloriegoal, calorieconsumed,calorieburned, fatgoal, proteingoal,carbohydrategoal FROM dailyDetails WHERE createddate = (SELECT MAX(createddate) FROM dailyDetails WHERE createddate <= ('"+formattedDate+"'))";
Cursor calorieConsumedQueryCursor = db.rawQuery(calorieConsumedQuery,null);
Cursor calorieBurnedQueryCursor = db.rawQuery(caloriBurnedQuery,null);
Cursor calorieDetailsQueryCursor = db.rawQuery(calorieDetailsQuery,null);
if (!calorieConsumedQueryCursor.isAfterLast()) {
calorieConsumedQueryCursor.moveToFirst();
while (!calorieConsumedQueryCursor.isAfterLast()) {
dbcalorie= (int) Math.round(calorieConsumedQueryCursor.getDouble(0));
dbtotalfat = (int) Math.round(calorieConsumedQueryCursor.getDouble(1));
dbtotalcarbs = (int) Math.round(calorieConsumedQueryCursor.getDouble(2));
dbtotalproteins = (int) Math.round(calorieConsumedQueryCursor.getDouble(3));
calorieConsumedQueryCursor.moveToNext();
}
}
if (!calorieBurnedQueryCursor.isAfterLast()) {
calorieBurnedQueryCursor.moveToFirst();
while (!calorieBurnedQueryCursor.isAfterLast()) {
dbcalorieburned = (int) Math.round(calorieBurnedQueryCursor.getDouble(0));
Log.e("calorie info"," dbcalorieburned: " + dbcalorieburned);
calorieBurnedQueryCursor.moveToNext();
}
}
if (!calorieDetailsQueryCursor.isAfterLast()) {
calorieDetailsQueryCursor.moveToFirst();
while (!calorieDetailsQueryCursor.isAfterLast()) {
calorie = (int) Math.round(calorieDetailsQueryCursor.getDouble(0));
ddcalorieconsumed = (int) Math.round(calorieDetailsQueryCursor.getDouble(1));
ddcalorieburned = (int) Math.round(calorieDetailsQueryCursor.getDouble(2));
dFat = (int) Math.round(calorieDetailsQueryCursor.getDouble(3));
dProteins = (int) Math.round(calorieDetailsQueryCursor.getDouble(4));
dCarbs = (int) Math.round(calorieDetailsQueryCursor.getDouble(5));
Log.e("Daily info"," ddcalorie: " + calorie);
Log.e("Daily info"," ddcalorieconsumed: " + ddcalorieconsumed);
Log.e("Daily info"," ddcalorieburned: " + ddcalorieburned);
Log.e("Daily info"," ddfatgoal: " + dFat);
Log.e("Daily info"," ddproteingoal: " + dProteins);
Log.e("Daily info"," ddcarbohydrategoal: " + dCarbs);
calorieDetailsQueryCursor.moveToNext();
}
}
calorieConsumedQueryCursor.close();
calorieBurnedQueryCursor.close();
calorieDetailsQueryCursor.close();
db.close();
}
private void selectnextdata() {
DatabaseHandler helper = new DatabaseHandler(getActivity());
SQLiteDatabase db = helper.getReadableDatabase();
String calorieConsumedQuery = "SELECT SUM(calorie) AS dbcalorie,SUM(fat) AS dbtotalfat,SUM(carbohydrate) AS dbtotalcarbs,SUM(protein)AS Totalprotein FROM Meal WHERE createddate = ('"+formattedDate+"')";
String caloriBurnedQuery = "SELECT SUM(calorieburned) AS dbcalorieburned FROM ExerciseData WHERE createddate = ('"+formattedDate+"')";
String calorieDetailsQuery = "SELECT caloriegoal, calorieconsumed,calorieburned, fatgoal, proteingoal,carbohydrategoal FROM dailyDetails WHERE createddate = (SELECT MAX(createddate) FROM dailyDetails WHERE createddate <= ('"+formattedDate+"'))";
Cursor calorieConsumedQueryCursor = db.rawQuery(calorieConsumedQuery,null);
Cursor calorieBurnedQueryCursor = db.rawQuery(caloriBurnedQuery,null);
Cursor calorieDetailsQueryCursor = db.rawQuery(calorieDetailsQuery,null);
if (!calorieConsumedQueryCursor.isAfterLast()) {
calorieConsumedQueryCursor.moveToFirst();
while (!calorieConsumedQueryCursor.isAfterLast()) {
dbcalorie= (int) Math.round(calorieConsumedQueryCursor.getDouble(0));
dbtotalfat = (int) Math.round(calorieConsumedQueryCursor.getDouble(1));
dbtotalcarbs = (int) Math.round(calorieConsumedQueryCursor.getDouble(2));
dbtotalproteins = (int) Math.round(calorieConsumedQueryCursor.getDouble(3));
calorieConsumedQueryCursor.moveToNext();
}
}
if (!calorieBurnedQueryCursor.isAfterLast()) {
calorieBurnedQueryCursor.moveToFirst();
while (!calorieBurnedQueryCursor.isAfterLast()) {
dbcalorieburned = (int) Math.round(calorieBurnedQueryCursor.getDouble(0));
Log.e("calorie info"," dbcalorieburned: " + dbcalorieburned);
calorieBurnedQueryCursor.moveToNext();
}
}
if (!calorieDetailsQueryCursor.isAfterLast()) {
calorieDetailsQueryCursor.moveToFirst();
while (!calorieDetailsQueryCursor.isAfterLast()) {
calorie = (int) Math.round(calorieDetailsQueryCursor.getDouble(0));
ddcalorieconsumed = (int) Math.round(calorieDetailsQueryCursor.getDouble(1));
ddcalorieburned = (int) Math.round(calorieDetailsQueryCursor.getDouble(2));
dFat = (int) Math.round(calorieDetailsQueryCursor.getDouble(3));
dProteins = (int) Math.round(calorieDetailsQueryCursor.getDouble(4));
dCarbs = (int) Math.round(calorieDetailsQueryCursor.getDouble(5));
Log.e("Daily info"," ddcalorie: " + calorie);
Log.e("Daily info"," ddcalorieconsumed: " + ddcalorieconsumed);
Log.e("Daily info"," ddcalorieburned: " + ddcalorieburned);
Log.e("Daily info"," ddfatgoal: " + dFat);
Log.e("Daily info"," ddproteingoal: " + dProteins);
Log.e("Daily info"," ddcarbohydrategoal: " + dCarbs);
calorieDetailsQueryCursor.moveToNext();
}
}
calorieConsumedQueryCursor.close();
calorieBurnedQueryCursor.close();
calorieDetailsQueryCursor.close();
db.close();
}
void drawGraph(int VALUES[]){
mRenderer.setApplyBackgroundColor(true);
mRenderer.setBackgroundColor(Color.WHITE);
mRenderer.setChartTitleTextSize(20);
mRenderer.setLabelsTextSize(15);
mRenderer.setLegendTextSize(20);
mRenderer.setMargins(new int[] { 20, 30, 15, 0 });
mRenderer.setStartAngle(90);
mRenderer.setPanEnabled(false);
mRenderer.setLabelsColor(Color.BLACK);
mRenderer.setLabelsTextSize(26);
for (int i = 0; i < VALUES.length; i++) {
mSeries.add(NAME_LIST[i] + " " + VALUES[i], VALUES[i]);
SimpleSeriesRenderer renderer = new SimpleSeriesRenderer();
renderer.setColor(COLORS[(mSeries.getItemCount() - 1) % COLORS.length]);
mRenderer.addSeriesRenderer(renderer);
}
if (mChartView != null) {
mChartView.repaint();
}
else if (mChartView == null) {
LinearLayout layout = (LinearLayout) rootView.findViewById(R.id.chart);
layout.setBackgroundColor(Color.WHITE);
mChartView = ChartFactory.getPieChartView(getActivity(), mSeries, mRenderer);
mChartView.setBackgroundColor(Color.DKGRAY);
mRenderer.setClickEnabled(true);
mRenderer.setSelectableBuffer(10);
mChartView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
SeriesSelection seriesSelection = mChartView.getCurrentSeriesAndPoint();
if (seriesSelection == null) {
Toast.makeText(getActivity(),"YOu have Clicked",Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(getActivity(),"Chart element data point index "+ (seriesSelection.getPointIndex()+1) + " was clicked" + " point value="+ seriesSelection.getValue(), Toast.LENGTH_SHORT).show();
}
}
});
mChartView.setOnLongClickListener(new View.OnLongClickListener() {
#Override
public boolean onLongClick(View v) {
SeriesSelection seriesSelection = mChartView.getCurrentSeriesAndPoint();
if (seriesSelection == null) {
Toast.makeText(getActivity(),"No chart element was long pressed", Toast.LENGTH_SHORT).show();;
return false;
} else {
Toast.makeText(getActivity(),"Chart element data point index "+ seriesSelection.getPointIndex()+ " was long pressed",Toast.LENGTH_SHORT).show();
return true;
}
}
});
layout.addView(mChartView, new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT));
}
else {
mChartView.repaint();
}
}
}
Add these lines inside drawGraph api
DefaultRenderer mRenderer = new DefaultRenderer(); //move the line
mSeries.clear()
Related
I use SQLite database to save data from different activities in my app. in the first activity I use the add method to create a row in the table and the next activities use update method to update the created columns. my previous question which is somehow similar can be found here :
Previous Question
Previously my problem was with not using setId. Now my problem is with the third activity. after calling the update method, the columns stay Null. I tried passing the id from NewProjectActivity to the MainActivity and then to the IntensityActivity but I don't know why the columns don't get updated. Here are the codes :
SQLite Helper:
public class SQLiteHelper extends SQLiteOpenHelper implements ProjectDAO {
public SQLiteHelper(Context context) {
super(context, "my_db", null, 1);
}
#Override
public void onCreate(SQLiteDatabase db) {
try {
db.execSQL("CREATE TABLE tbl_project_info (id INTEGER PRIMARY KEY," +
"name TEXT," +
"company_name TEXT," +
"address TEXT," +
"length1 TEXT," +
"length2 TEXT," +
"length3 TEXT," +
"length4 TEXT," +
"length5 TEXT," +
"diameter1 Text," +
"diameter2 Text," +
"diameter3 Text," +
"diameter4 Text," +
"diameter5 Text," +
"surface Text," +
"soilResistance Text," +
"intensity Text," +
"allowedIntensity Text," +
"intensityResult Text)");
} catch (SQLiteException e) {
Log.e("SQLITE", "onCreate: " + e.toString());
}
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
}
#Override
public long addProject(Project project) {
SQLiteDatabase db = getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put("name", project.getName());
contentValues.put("company_name", project.getCompany_name());
contentValues.put("address", project.getAddress());
contentValues.put("length1", project.getLength1());
contentValues.put("length2", project.getLength2());
contentValues.put("length3", project.getLength3());
contentValues.put("length4", project.getLength4());
contentValues.put("length5", project.getLength5());
contentValues.put("diameter1", project.getDiameter1());
contentValues.put("diameter2", project.getDiameter2());
contentValues.put("diameter3", project.getDiameter3());
contentValues.put("diameter4", project.getDiameter4());
contentValues.put("diameter5", project.getDiameter5());
contentValues.put("surface", project.getSurface());
contentValues.put("soilResistance", project.getSoilResistance());
contentValues.put("intensity", project.getIntensity());
contentValues.put("allowedIntensity", project.getAllowedIntensity());
contentValues.put("intensityResult", project.getIonS());
long result = db.insert("tbl_project_info", null, contentValues);
db.close();
return result;
}
#Override
public int getProjectsCount() {
SQLiteDatabase db = getReadableDatabase();
Cursor cursor = db.rawQuery("SELECT * FROM tbl_project_info", null);
int count = cursor.getCount();
cursor.close();
db.close();
return count;
}
#Override
public boolean updateProject(Project project) {
SQLiteDatabase db = getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put("length1", project.getLength1());
contentValues.put("length2", project.getLength2());
contentValues.put("length3", project.getLength3());
contentValues.put("length4", project.getLength4());
contentValues.put("length5", project.getLength5());
contentValues.put("diameter1", project.getDiameter1());
contentValues.put("diameter2", project.getDiameter2());
contentValues.put("diameter3", project.getDiameter3());
contentValues.put("diameter4", project.getDiameter4());
contentValues.put("diameter5", project.getDiameter5());
contentValues.put("surface", project.getSurface());
contentValues.put("soilResistance", project.getSoilResistance());
contentValues.put("intensity", project.getIntensity());
contentValues.put("allowedIntensity", project.getAllowedIntensity());
contentValues.put("intensityResult", project.getIonS());
db.update("tbl_project_info", contentValues, "id = ?", new String[]{String.valueOf(project.getId())});
db.close();
return true;
}
#Override
public List<Project> getAllProjects() {
List<Project> projects = new ArrayList<>();
SQLiteDatabase db = getReadableDatabase();
Cursor cursor = db.rawQuery("SELECT * FROM tbl_project_info", null);
if (cursor.moveToFirst()) {
do {
Project project = new Project();
project.setName(cursor.getString(0));
project.setCompany_name(cursor.getString(1));
project.setAddress(cursor.getString(2));
projects.add(project);
} while (cursor.moveToNext());
}
return projects;
}
}
NewProjectActivity :
public class NewProjectActivity extends AppCompatActivity {
private ProjectDAO projectDAO;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_new_project);
projectDAO = DBInjector.provideProjectDao(this);
setupViews();
}
private void setupViews() {
final EditText projectNameET = findViewById(R.id.et_newProject_projectName);
final EditText companyNameET = findViewById(R.id.et_newProject_companyName);
final EditText addressET = findViewById(R.id.et_newProject_address);
Button saveInfoBTN = findViewById(R.id.btn_newProject_saveInfo);
saveInfoBTN.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
long projectID = -1;
if (projectNameET.length() > 0) {
if (companyNameET.length() > 0) {
if (addressET.length() > 0) {
Project project = new Project();
project.setName(projectNameET.getText().toString());
project.setCompany_name(companyNameET.getText().toString());
project.setAddress(addressET.getText().toString());
projectID = projectDAO.addProject(project);
if (projectID > 0){
Toast.makeText(NewProjectActivity.this, "Success", Toast.LENGTH_SHORT).show();
}else {
Toast.makeText(NewProjectActivity.this, "Failed", Toast.LENGTH_SHORT).show();
}
}
}else {
companyNameET.setError("company name not entered");
}
}else{
projectNameET.setError("project name not entered");
}
PersonalInfoSharedPrefManager manager = new PersonalInfoSharedPrefManager(NewProjectActivity.this);
manager.setID(projectID);
Intent intent = new Intent(NewProjectActivity.this,MainActivity.class);
intent.putExtra("IE_PROJECTID",projectID);
startActivity(intent);
}
});
}
}
MainActivity :
public class MainActivity extends AppCompatActivity {
private ProjectDAO projectDAO;
private long mProjectID;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
projectDAO = DBInjector.provideProjectDao(this);
mProjectID = getIntent().getLongExtra("IE_PROJECTID",0);
final EditText lengthET1 = findViewById(R.id.et_main_length1);
final EditText lengthET2 = findViewById(R.id.et_main_length2);
final EditText lengthET3 = findViewById(R.id.et_main_length3);
final EditText lengthET4 = findViewById(R.id.et_main_length4);
final EditText lengthET5 = findViewById(R.id.et_main_length5);
final EditText diameterET1 = findViewById(R.id.et_main_diameter1);
final EditText diameterET2 = findViewById(R.id.et_main_diameter2);
final EditText diameterET3 = findViewById(R.id.et_main_diameter3);
final EditText diameterET4 = findViewById(R.id.et_main_diameter4);
final EditText diameterET5 = findViewById(R.id.et_main_diameter5);
Button calculateButton = findViewById(R.id.btn_main_calculate);
calculateButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
float Le1 = 0;
if (lengthET1.length() > 0) {
String L1 = lengthET1.getText().toString();
Le1 = Float.parseFloat(L1);
}
float Di1 = 0;
if (diameterET1.length() > 0) {
String D1 = diameterET1.getText().toString();
Di1 = Float.parseFloat(D1);
}
float Le2 = 0;
if (lengthET2.length() > 0) {
String L2 = lengthET2.getText().toString();
Le2 = Float.parseFloat(L2);
}
float Di2 = 0;
if (diameterET2.length() > 0) {
String D2 = diameterET2.getText().toString();
Di2 = Float.parseFloat(D2);
}
float Le3 = 0;
if (lengthET3.length() > 0) {
String L3 = lengthET3.getText().toString();
Le3 = Float.parseFloat(L3);
}
float Di3 = 0;
if (diameterET3.length() > 0) {
String D3 = diameterET3.getText().toString();
Di3 = Float.parseFloat(D3);
}
float Le4 = 0;
if (lengthET4.length() > 0) {
String L4 = lengthET4.getText().toString();
Le4 = Float.parseFloat(L4);
}
float Di4 = 0;
if (diameterET4.length() > 0) {
String D4 = diameterET4.getText().toString();
Di4 = Float.parseFloat(D4);
}
float Le5 = 0;
if (lengthET5.length() > 0) {
String L5 = lengthET5.getText().toString();
Le5 = Float.parseFloat(L5);
}
float Di5 = 0;
if (diameterET5.length() > 0) {
String D5 = diameterET5.getText().toString();
Di5 = Float.parseFloat(D5);
}
final float Surface1 = (float) (Le1 * Di1 * Math.PI);
final float Surface2 = (float) (Le2 * Di2 * Math.PI);
final float Surface3 = (float) (Le3 * Di3 * Math.PI);
final float Surface4 = (float) (Le4 * Di4 * Math.PI);
final float Surface5 = (float) (Le5 * Di5 * Math.PI);
final float Surface = Surface1 + Surface2 + Surface3 + Surface4 + Surface5;
long projectID = -1;
Intent intent = new Intent(MainActivity.this, IntensityActivity.class);
if (Surface == 0) {
Toast.makeText(MainActivity.this, "No numbers are entered", Toast.LENGTH_SHORT).show();
} else {
intent.putExtra("Result", Surface);
intent.putExtra("IE_PROJECTID",projectID);
startActivity(intent);
}
PersonalInfoSharedPrefManager manager = new PersonalInfoSharedPrefManager(MainActivity.this);
manager.setSuface(Surface);
Project project = new Project();
project.setId(mProjectID);
project.setLength1(lengthET1.getText().toString());
project.setDiameter1(diameterET1.getText().toString());
project.setLength2(lengthET2.getText().toString());
project.setDiameter2(diameterET2.getText().toString());
project.setLength3(lengthET3.getText().toString());
project.setDiameter3(diameterET3.getText().toString());
project.setLength4(lengthET4.getText().toString());
project.setDiameter4(diameterET4.getText().toString());
project.setLength5(lengthET5.getText().toString());
project.setDiameter5(diameterET5.getText().toString());
project.setSurface(String.valueOf(Surface));
projectDAO.updateProject(project);
}
});
}
}
IntensityActivity :
public class IntensityActivity extends AppCompatActivity {
private ProjectDAO projectDAO;
private long mProjectID;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_intensity);
projectDAO = DBInjector.provideProjectDao(this);
mProjectID = getIntent().getLongExtra("IE_PROJECTID",0);
final float Result = getIntent().getFloatExtra("Result",0);
final Button resistanceBTN1 = findViewById(R.id.btn_intensity_R1);
final Button resistanceBTN2 = findViewById(R.id.btn_intensity_R2);
final Button resistanceBTN3 = findViewById(R.id.btn_intensity_R3);
final Button resistanceBTN4 = findViewById(R.id.btn_intensity_R4);
final Button resistanceBTN5 = findViewById(R.id.btn_intensity_R5);
final View RL = findViewById(R.id.rl_intensity_allowedIntensity);
final TextView allowedResistance = findViewById(R.id.tv_intensity_allowedIntensityNumber);
final TextView surfaceNumber = findViewById(R.id.tv_intensity_surfaceNumber);
final EditText intensityNumber = findViewById(R.id.et_intensity_intensityNumber);
Button calculateButton = findViewById(R.id.btn_intensity_calculate);
final Button goToVoltageButton = findViewById(R.id.btn_intensity_goToVoltage);
final TextView formulaResultNumber = findViewById(R.id.tv_intensity_resultNumber);
String Sur = Float.toString(Result);
surfaceNumber.setText(Sur);
final double R1 = Result*0.250;
final double R2 = Result*0.125;
final double R3 = Result*0.050;
final double R4 = Result*0.025;
final double R5 = Result*0.010;
final String Re1 = Double.toString(R1);
final String Re2 = Double.toString(R2);
final String Re3 = Double.toString(R3);
final String Re4 = Double.toString(R4);
final String Re5 = Double.toString(R5);
resistanceBTN1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
RL.setVisibility(View.VISIBLE);
allowedResistance.setText(Re1);
}
});
resistanceBTN2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
RL.setVisibility(View.VISIBLE);
allowedResistance.setText(Re2);
}
});
resistanceBTN3.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
RL.setVisibility(View.VISIBLE);
allowedResistance.setText(Re3);
}
});
resistanceBTN4.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
RL.setVisibility(View.VISIBLE);
allowedResistance.setText(Re4);
}
});
resistanceBTN5.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
RL.setVisibility(View.VISIBLE);
allowedResistance.setText(Re5);
}
});
calculateButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String I = intensityNumber.getText().toString();
float In = Float.parseFloat(I);
float R = In/Result;
String Res = String.valueOf(R);
formulaResultNumber.setText(Res);
goToVoltageButton.setVisibility(View.VISIBLE);
PersonalInfoSharedPrefManager manager = new PersonalInfoSharedPrefManager(IntensityActivity.this);
manager.setIntensity(In);
}
});
goToVoltageButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(IntensityActivity.this,SimpleVoltage.class);
startActivity(intent);
Project project = new Project();
project.setId(mProjectID);
project.setAllowedIntensity(String.valueOf(allowedResistance));
project.setIntensity(intensityNumber.getText().toString());
projectDAO.updateProject(project);
}
});
}
}
From MainActivity to IntensityActivity, What I found is that you are always passing -1 in Project ID
final float Surface = Surface1 + Surface2 + Surface3 + Surface4 + Surface5;
long projectID = -1;
Intent intent = new Intent(MainActivity.this, IntensityActivity.class);
if (Surface == 0) {
Toast.makeText(MainActivity.this, "No numbers are entered", Toast.LENGTH_SHORT).show();
} else {
intent.putExtra("Result", Surface);
intent.putExtra("IE_PROJECTID",projectID);
startActivity(intent);
}
Instead you can pass the same ID you have got on this activity from Intent
Just update your code in MainActivity as below and pass mProjectID.
final float Surface = Surface1 + Surface2 + Surface3 + Surface4 + Surface5;
long projectID = -1;
Intent intent = new Intent(MainActivity.this, IntensityActivity.class);
if (Surface == 0) {
Toast.makeText(MainActivity.this, "No numbers are entered", Toast.LENGTH_SHORT).show();
} else {
intent.putExtra("Result", Surface);
intent.putExtra("IE_PROJECTID",mProjectID);
startActivity(intent);
}
Hope this will help.
try this way in your update method,
db.update("tbl_project_info", contentValues, "id="+String.valueOf(project.getId()), null);
Also you need to change following line into MainActivity.java
long projectID = -1;
to
long projectID = mProjectID;
// i have two button for increasing and decreasing the quantity, after increasing or decreasing the value i want to calculate price from each row but it is not giving correct value.Also the quantity getting changed while scrolling .Mostly the above said problem occurs whenever the size of listview is more than screen size.
public class Baseddapter extends BaseAdapter
{
#Override
public int getCount()
{
return prodetailarray.size();
}
#Override
public Object getItem(int i)
{
// Log.d("item_value",""+prodetailarray.get(i).getPrice());
return null;
}
#Override
public long getItemId(int i)
{
return 0;
}
#Override
public View getView(int position, View convertView, ViewGroup parent)
{
listrowposition = position;
final ViewHolder holder;
if (convertView == null)
{
LayoutInflater inflater = getLayoutInflater();
convertView = inflater.inflate(R.layout.singlerowbill_detail, null);
holder = new ViewHolder();
holder.name = (TextView) convertView.findViewById(R.id.txtproname_prodetail);
holder.sellprice = (TextView) convertView.findViewById(R.id.txtprice_prodetail);
holder.proid = (TextView) convertView.findViewById(R.id.txtproid_prodetail);
holder.qty = (TextView) convertView.findViewById(R.id.txtquntty_prodetail);
holder.imgplus = (ImageView) convertView.findViewById(R.id.imgplus_prodetail);
holder.imgminus = (ImageView) convertView.findViewById(R.id.imgminus_prodetail);
holder.singlerowprice = (TextView) convertView.findViewById(R.id.txtsinglerow_price);
holder.baseprice = (TextView) convertView.findViewById(R.id.txt_base_price_prodetail);
holder.taxid = (TextView) convertView.findViewById(R.id.txt_taxid_prodetail);
holder.taxname = (TextView) convertView.findViewById(R.id.txt_taxname_prodetail);
holder.taxval = (TextView) convertView.findViewById(R.id.txt_taxval_prodetail);
// holder.singlerowprice.addTextChangedListener(new MytextWatcher(convertView));
holder.delete = (ImageView) convertView.findViewById(R.id.txtdeleterow);
holder.txtkg = (TextView) convertView.findViewById(R.id.txtkg);
holder.whole_qntty = (TextView) convertView.findViewById(R.id.txt_whole_qntty_prodetail);
holder.delete.setTag(position);
holder.circularImageView = (CircularImageView) convertView.findViewById(R.id.productImage_billdetail);
holder.linearLayout = (LinearLayout) convertView.findViewById(R.id.linearkg);
holder.name.setTypeface(light);
holder.singlerowprice.setTypeface(light);
holder.baseprice.setTypeface(light);
holder.qty.setTypeface(light);
//holder.qty.setTag(position);
convertView.setTag(holder);
}
else
{
holder = (ViewHolder) convertView.getTag();
}
base_price = prodetailarray.get(listrowposition).getBaseprice();
Log.d("baseprice==", "***" + base_price);
holder.baseprice.setText(prodetailarray.get(listrowposition).getBaseprice());
//this means if qnty contain only number means add as unit otherwise add as kg
if(prodetailarray.get(listrowposition).getQntity().matches("[0-9]+"))
{
holder.qty.setText(prodetailarray.get(position).getQntity());
//holder.linearLayout.setVisibility(View.VISIBLE);
holder.imgplus.setVisibility(View.VISIBLE);
holder.imgminus.setVisibility(View.VISIBLE);
// holder.txtkg.setVisibility(View.GONE);
Log.d("qntty_kg??",""+prodetailarray.get(listrowposition).getQntity());
}
else
{
// holder.linearLayout.setVisibility(View.GONE);
holder.imgplus.setVisibility(View.GONE);
holder.imgminus.setVisibility(View.GONE);
// holder.txtkg.setVisibility(View.VISIBLE);
holder.qty.setText(""+prodetailarray.get(listrowposition).getQntity());
Log.d("qntty_kg==",""+prodetailarray.get(listrowposition).getQntity());
// Toast.makeText(Bill_details.this,""+prodetailarray.get(position).getQntity(),Toast.LENGTH_LONG).show();
}
holder.name.setText(prodetailarray.get(listrowposition).getProductname());
holder.sellprice.setText(getResources().getString(R.string.Rs)+" "+prodetailarray.get(position).getPrice());
holder.taxid.setText(prodetailarray.get(listrowposition).getTaxid());
holder.taxname.setText(prodetailarray.get(listrowposition).getTaxname());
holder.taxval.setText(prodetailarray.get(listrowposition).getTaxvalue());
holder.whole_qntty.setText(prodetailarray.get(listrowposition).getWhole_qntty());
holder.proid.setText(prodetailarray.get(listrowposition).getProducuid());
final String str=prodetailarray.get(listrowposition).getQntity();
Double q = Double.parseDouble(str.replaceAll("KG", ""));
holder.singlerowprice.setText(getResources().getString(R.string.Rs)+" " + Double.parseDouble(prodetailarray.get(listrowposition).getPrice()) * q);
drawable = mDrawableBuilder.build(String.valueOf(holder.name.getText().toString().trim().toUpperCase().charAt(0)),
mColorGenerator.getColor((holder.name.getText().toString().trim().charAt(0))));
holder.circularImageView.setImageDrawable(drawable);
holder.delete.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View view)
{
total_item = totalquantity-1;
totalquantity=total_item;
Integer index = (Integer) view.getTag();
Log.d("indexval==","delete"+index.intValue());
prodetailarray.remove(index.intValue());
adapter.notifyDataSetChanged();
listView.invalidateViews();
Log.d("listCount==",""+listView.getCount());
// totalprice=0;
Double add = 0.0;
Double pr = 0.0;
// listView.invalidateViews();
if (listView.getCount() == 0)
{
totalitem.setText("0 Items");
totalamount.setText( getResources().getString(R.string.Rs)+" 0");
editor.remove("count");
editor.remove("price");
editor.commit();
}
Log.d("liistvisiblepos==",""+(listView.getLastVisiblePosition()-listView.getFirstVisiblePosition())) ;
for (int i = 0; i < listView.getCount(); i++)
{
// this if is for after delete item it will take first item so we dont want like this
if(index.intValue() != i)
{
/* View v = listView.getChildAt(i);
TextView tvquan = (TextView) v.findViewById(R.id.txtquntty_prodetail);
TextView tvprice = (TextView) v.findViewById(R.id.txtsinglerow_price);
*/
String str = holder.qty.getText().toString().trim();
Double p = Double.parseDouble(str.replaceAll(getResources().getString(R.string.Rs), ""));
pr = pr + p;
totalitem.setText("" + total_item + " Items");
totalamount.setText(getResources().getString(R.string.Rs) + " " + pr);
// Log.d("listitemcount==", "tvquan==" + tvquan.getText().toString() + "add==" + add + "price" + pr + "p==" + p);
}
}
}
});
holder.imgplus.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View view)
{
View v1=view;
PLUSMINUS = 100;
if(holder.qty.getText().toString().matches("[0-9]+"))
{
plus_qnty = Integer.parseInt(holder.qty.getText().toString());
Log.d("plus_qnty==",""+plus_qnty);
//this is for check the quantity that useer enter is not more than qntty in stock
Log.d("whole_qnt_plus==",""+holder.whole_qntty.getText().toString());
whole_qnt= Integer.parseInt(holder.whole_qntty.getText().toString());
Log.d("whole_qnt_plus==",""+whole_qnt);
plus_qnty = plus_qnty + 1;
if(plus_qnty>whole_qnt)
{
Toast.makeText(getApplicationContext(), getResources().getString(R.string.outofstock), Toast.LENGTH_LONG).show();
}
else
{
prodetailarray.get(listrowposition).setQntity(String.valueOf(plus_qnty));
holder.qty.setText("" + plus_qnty);
//remove all the text except price (integer value)
String str=holder.sellprice.getText().toString().trim();
Double sell_price= Double.parseDouble(str.replaceAll(getResources().getString(R.string.Rs), ""));
holder.singlerowprice.setText(getResources().getString(R.string.Rs)+" " + Double.parseDouble(holder.qty.getText().toString()) * sell_price);
prodetailarray.get(listrowposition).setQntity(String.valueOf(plus_qnty));
prodetailarray.get(listrowposition).setBaseprice("" + Double.parseDouble(base_price) * plus_qnty);
}
/*for calculate value after change if any change*/
Double add = 0.0;
Double pr = 0.0;
for (int i = 0;i < listView.getCount(); i++)
{
Log.d("listviewcount==",""+listView.getCount());
View v = listView.getAdapter().getView(i,null,null);
TextView tvquan = (TextView) v.findViewById(R.id.txtquntty_prodetail);
TextView tvprice = (TextView) v.findViewById(R.id.txtsinglerow_price);
// String str_qun=tvquan.getText().toString().trim();
String str_qun=tvquan.getText().toString().trim();
Log.d("listviewcount==",""+str_qun);
Double c = Double.parseDouble(str_qun.replaceAll("KG", ""));
add = c + add;
String str = tvprice.getText().toString().trim();
// String str = holder.singlerowprice.getText().toString().trim();
Log.d("str_qun==",""+str_qun+str);
Double p = Double.parseDouble(str.replaceAll(getResources().getString(R.string.Rs), ""));
pr = pr + p;
// Log.d("listitemcount==", "tvquan==" + tvquan.getText().toString() + "add==" + add + "price" + pr);
totalamount.setText(getResources().getString(R.string.Rs) +" "+ pr);
}
}
else {
}
}
});
holder.imgminus.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
PLUSMINUS = 200;
if(holder.qty.getText().toString().matches("[0-9]+"))
{
minus_qnty = Integer.parseInt(holder.qty.getText().toString());
if (minus_qnty == 1)
{
// holder.qty.setText(""+);
}
else
{
minus_qnty = minus_qnty - 1;
holder.qty.setText("" + minus_qnty);
String str=holder.sellprice.getText().toString();
Double sell_price= Double.parseDouble(str.replaceAll(getResources().getString(R.string.Rs), ""));
holder.singlerowprice.setText(getResources().getString(R.string.Rs)+" " + Double.parseDouble(holder.qty.getText().toString()) * sell_price);
prodetailarray.get(listrowposition).setQntity(String.valueOf(minus_qnty));
prodetailarray.get(listrowposition).setBaseprice("" + Double.parseDouble(base_price) * minus_qnty);
}
/*for calculate value after change if any change*/
Double add = 0.0;
Double pr = 0.0;
for (int i = 0; i <listView.getCount(); i++)
{
View v = listView.getAdapter().getView(i,null,null);
TextView tvquan = (TextView) v.findViewById(R.id.txtquntty_prodetail);
TextView tvprice = (TextView) v.findViewById(R.id.txtsinglerow_price);
String str_qun=tvquan.getText().toString().trim();
Double c = Double.parseDouble(str_qun.replaceAll("KG", ""));
add = c + add;
String str = tvprice.getText().toString().trim();
Double p = Double.parseDouble(str.replaceAll(getResources().getString(R.string.Rs), ""));
pr = pr + p;
// Log.d("listitemcount==", "tvquan==" + tvquan.getText().toString() + "add==" + add + "price" + pr);
totalamount.setText(getResources().getString(R.string.Rs) +" "+ pr);
}
}
else
{
}
}
});
if(!prodetailarray.get(listrowposition).getQntity().matches("[0-9]+"))
{
holder.qty.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View view)
{
final Integer index = (Integer) view.getTag();
Log.d("indexval==","index==="+index);
final Dialog dialog_item = new Dialog(Bill_details.this);
dialog_item.setContentView(R.layout.add_item_dialog);
dialog_item.getWindow().setLayout(AppBarLayout.LayoutParams.FILL_PARENT, AppBarLayout.LayoutParams.WRAP_CONTENT);
final EditText edt_enter_qntty = (EditText) dialog_item.findViewById(R.id.txtqntty_item_dialog);
TextView ok = (TextView) dialog_item.findViewById(R.id.txtok_item_dialog);
ok.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View view)
{
if(edt_enter_qntty.getText().toString().equals(""))
{
}
else
{
Double dialog_qntty= Double.parseDouble(edt_enter_qntty.getText().toString());
// PLUSMINUS = 100;
kg_qntty = dialog_qntty;
//this is for checking entered qunnt is not more than avail qntty
String whole_qnt=holder.whole_qntty.getText().toString();
String whole_qnt_replce= (whole_qnt.replaceAll("KG", ""));
whole_qnt_kg= Double.parseDouble(whole_qnt_replce);
Log.d("whole_qnt_kg==",""+whole_qnt_kg);
if(kg_qntty>whole_qnt_kg)
{
Toast.makeText(getApplicationContext(), getResources().getString(R.string.outofstock), Toast.LENGTH_LONG).show();
}
else
{
prodetailarray.get(listrowposition).setQntity(String.valueOf(kg_qntty));
holder.qty.setText("" + kg_qntty+"KG");
//remove all the text except price (integer value)
String str_qnty=holder.qty.getText().toString();
Double qty= Double.parseDouble(str_qnty.replaceAll("KG", ""));
String str=holder.sellprice.getText().toString();
Double sell_price= Double.parseDouble(str.replaceAll(getResources().getString(R.string.Rs), ""));
holder.singlerowprice.setText(getResources().getString(R.string.Rs)+" " + qty * sell_price);
prodetailarray.get(listrowposition).setQntity(String.valueOf(kg_qntty));
prodetailarray.get(listrowposition).setBaseprice("" + Double.parseDouble(base_price) * kg_qntty);
}
/*for calculate value after change if any change*/
Double add = 0.0;
Double pr = 0.0;
for (int i = 0;i <listView.getCount(); i++)
{
View v = listView.getAdapter().getView(i,null,null);
TextView tvquan = (TextView) v.findViewById(R.id.txtquntty_prodetail);
TextView tvprice = (TextView) v.findViewById(R.id.txtsinglerow_price);
String str_quan=tvquan.getText().toString().trim();
Log.d("strqn",str_quan);
String c = (str_quan.replaceAll("KG", ""));
Log.d("strqn", "" + c);
add = Double.parseDouble(c) + add;
String str_pri=tvprice.getText().toString().trim();
Double p= Double.parseDouble(str_pri.replaceAll(getResources().getString(R.string.Rs), ""));
pr = pr + p;
Log.d("total_qntty", "tvquan==" + tvquan.getText().toString() + "add==" + add + "price" + pr);
// totalitem.setText("" + add+" Items");
totalamount.setText(getResources().getString(R.string.Rs) +" "+ pr);
}
}
dialog_item.dismiss();
}
});
dialog_item.show();
}
});
}
return convertView;
}
#Override
public int getViewTypeCount() {
return getCount();
}
#Override
public int getItemViewType(int position) {
return position;
}
}
Never update an item view in a list from the event handler (controller).
It looks like you are correctly updating the model (prodetailarray), but in an onClick or any event handler, all you want to do is update the model and then call notifyDataSetChanged(). This will inform your list view that the model has changed, and the list view will regenerate item views based on the new model data.
If that's not sufficient to solve your problem, you'll need to post your entire adapter code so we can identify the problem.
//see below getview method which I updated .
public View getView(final int position, View convertView, ViewGroup parent)
{
listrowposition = position;
final ViewHolder holder;
if (convertView == null)
{
LayoutInflater inflater = getLayoutInflater();
convertView = inflater.inflate(R.layout.singlerowbill_detail, null);
holder = new ViewHolder();
holder.name = (TextView) convertView.findViewById(R.id.txtproname_prodetail);
holder.sellprice = (TextView) convertView.findViewById(R.id.txtprice_prodetail);
holder.proid = (TextView) convertView.findViewById(R.id.txtproid_prodetail);
holder.qty = (TextView) convertView.findViewById(R.id.txtquntty_prodetail);
holder.imgplus = (ImageView) convertView.findViewById(R.id.imgplus_prodetail);
holder.imgminus = (ImageView) convertView.findViewById(R.id.imgminus_prodetail);
holder.singlerowprice = (TextView) convertView.findViewById(R.id.txtsinglerow_price);
holder.baseprice = (TextView) convertView.findViewById(R.id.txt_base_price_prodetail);
holder.taxid = (TextView) convertView.findViewById(R.id.txt_taxid_prodetail);
holder.taxname = (TextView) convertView.findViewById(R.id.txt_taxname_prodetail);
holder.taxval = (TextView) convertView.findViewById(R.id.txt_taxval_prodetail);
// holder.singlerowprice.addTextChangedListener(new MytextWatcher(convertView));
holder.delete = (ImageView) convertView.findViewById(R.id.txtdeleterow);
holder.txtkg = (TextView) convertView.findViewById(R.id.txtkg);
holder.whole_qntty = (TextView) convertView.findViewById(R.id.txt_whole_qntty_prodetail);
holder.circularImageView = (CircularImageView) convertView.findViewById(R.id.productImage_billdetail);
holder.linearLayout = (LinearLayout) convertView.findViewById(R.id.linearkg);
holder.name.setTypeface(light);
holder.singlerowprice.setTypeface(light);
holder.baseprice.setTypeface(light);
holder.qty.setTypeface(light);
convertView.setTag(holder);
}
else
{
holder = (ViewHolder) convertView.getTag();
}
base_price = prodetailarray.get(listrowposition).getBaseprice();
holder.qty.setTag(listrowposition);
holder.delete.setTag(listrowposition);
holder.imgplus.setTag(listrowposition);
holder.imgminus.setTag(listrowposition);
Log.d("baseprice==", "***" + base_price);
holder.baseprice.setText(prodetailarray.get(listrowposition).getBaseprice());
//this means if qnty contain only number means add as unit otherwise add as kg
if(prodetailarray.get(listrowposition).getQntity().matches("[0-9]+"))
{
holder.qty.setText(prodetailarray.get(listrowposition).getQntity());
//
holder.imgplus.setVisibility(View.VISIBLE);
holder.imgminus.setVisibility(View.VISIBLE);
//
Log.d("qntty_kg??",""+prodetailarray.get(listrowposition).getQntity());
}
else
{
holder.imgplus.setVisibility(View.GONE);
holder.imgminus.setVisibility(View.GONE);
//
holder.qty.setText(""+prodetailarray.get(listrowposition).getQntity());
Log.d("qntty_kg==",""+prodetailarray.get(listrowposition).getQntity());
}
holder.name.setText(prodetailarray.get(listrowposition).getProductname());
holder.sellprice.setText(getResources().getString(R.string.Rs)+" "+prodetailarray.get(listrowposition).getPrice());
holder.taxid.setText(prodetailarray.get(listrowposition).getTaxid());
holder.taxname.setText(prodetailarray.get(listrowposition).getTaxname());
holder.taxval.setText(prodetailarray.get(listrowposition).getTaxvalue());
holder.whole_qntty.setText(prodetailarray.get(listrowposition).getWhole_qntty());
holder.proid.setText(prodetailarray.get(listrowposition).getProducuid());
final String str=prodetailarray.get(listrowposition).getQntity();
Double q = Double.parseDouble(str.replaceAll("KG", ""));
holder.singlerowprice.setText(getResources().getString(R.string.Rs)+" " + Double.parseDouble(prodetailarray.get(listrowposition).getPrice()) * q);
drawable = mDrawableBuilder.build(String.valueOf(holder.name.getText().toString().trim().toUpperCase().charAt(0)),
mColorGenerator.getColor((holder.name.getText().toString().trim().charAt(0))));
holder.circularImageView.setImageDrawable(drawable);
holder.delete.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View view)
{
total_item = totalquantity-1;
totalquantity=total_item;
Integer index = (Integer) view.getTag();
Log.d("indexval==","delete"+index.intValue());
prodetailarray.remove(index.intValue());
adapter.notifyDataSetChanged();
listView.invalidateViews();
Log.d("listCount==",""+listView.getCount());
Double add = 0.0;
Double pr = 0.0;
if (listView.getCount() == 0)
{
totalitem.setText("0 Items");
totalamount.setText( getResources().getString(R.string.Rs)+" 0");
editor.remove("count");
editor.remove("price");
editor.commit();
}
for (int i = 0; i < listView.getCount(); i++)
{
// this if is for after delete item it will take first item so we dont want like this
View v = listView.getAdapter().getView(i,null,listView);
if(v==null)
{
return;
}
TextView tvquan = (TextView) v.findViewById(R.id.txtquntty_prodetail);
TextView tvprice = (TextView) v.findViewById(R.id.txtsinglerow_price);
String str_qun=tvquan.getText().toString().trim();
Double c = Double.parseDouble(str_qun.replaceAll("KG", ""));
add = c + add;
String str = tvprice.getText().toString().trim();
Double p = Double.parseDouble(str.replaceAll(getResources().getString(R.string.Rs), ""));
pr = pr + p;
totalitem.setText("" + total_item + " Items");
totalamount.setText(getResources().getString(R.string.Rs) + " " + pr);
Log.d("listitemcount==", "tvquan==" + tvquan.getText().toString() + "add==" + add + "price" + pr + "p==" + p);
}
}
});
holder.imgplus.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View view)
{
int in=(Integer) view.getTag();
PLUSMINUS = 100;
if(holder.qty.getText().toString().matches("[0-9]+"))
{
plus_qnty = Integer.parseInt(holder.qty.getText().toString());
Log.d("plus_qnty==",""+plus_qnty);
//this is for check the quantity that useer enter is not more than qntty in stock
Log.d("whole_qnt_plus==",""+holder.whole_qntty.getText().toString());
whole_qnt= Integer.parseInt(holder.whole_qntty.getText().toString());
Log.d("whole_qnt_plus==",""+whole_qnt);
plus_qnty = plus_qnty + 1;
if(plus_qnty>whole_qnt)
{
Toast.makeText(getApplicationContext(), getResources().getString(R.string.outofstock), Toast.LENGTH_LONG).show();
}
else
{
for(int i=0;i<prodetailarray.size();i++){
Log.d("proarr==","getQntity=="+""+prodetailarray.get(i).getQntity()+"baseprice=="+prodetailarray.get(i).getBaseprice());
}
holder.qty.setText("" + plus_qnty);
//remove all the text except price (integer value)
String str=holder.sellprice.getText().toString().trim();
Double sell_price= Double.parseDouble(str.replaceAll(getResources().getString(R.string.Rs), ""));
holder.singlerowprice.setText(getResources().getString(R.string.Rs)+" " + Double.parseDouble(holder.qty.getText().toString()) * sell_price);
Bills_Activity.productlistarray.set(position,);
prodetailarray.get(in).setQntity(String.valueOf(plus_qnty));
prodetailarray.get(in).setBaseprice("" + Double.parseDouble(base_price) * plus_qnty);
for(int i=0;i<prodetailarray.size();i++)
{
Log.d("proarr=="," after_getQntity=="+""+prodetailarray.get(i).getQntity()+"baseprice=="+prodetailarray.get(i).getBaseprice());
}
}
/*for calculate value after change if any change*/
Double add = 0.0;
Double pr = 0.0;
for (int i = 0;i <listView.getCount(); i++)
{
View v = listView.getAdapter().getView(i,null,listView);
if(v==null)
{
return;
}
TextView tvquan = (TextView) v.findViewById(R.id.txtquntty_prodetail);
TextView tvprice = (TextView) v.findViewById(R.id.txtsinglerow_price);
String str_qun=tvquan.getText().toString().trim();
Double c = Double.parseDouble(str_qun.replaceAll("KG", ""));
add = c + add;
String str = tvprice.getText().toString().trim();
Double p = Double.parseDouble(str.replaceAll(getResources().getString(R.string.Rs), ""));
pr = pr + p;
Log.d("listitemcount==", "tvquan==" + tvquan.getText().toString() + "add==" + add + "price" + pr);
totalamount.setText(getResources().getString(R.string.Rs) +" "+ pr);
}
}
else
{
}
}
});
holder.imgminus.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
PLUSMINUS = 200;
int in=(Integer) view.getTag();
if(holder.qty.getText().toString().matches("[0-9]+"))
{
minus_qnty = Integer.parseInt(holder.qty.getText().toString());
if (minus_qnty == 1)
{
}
else
{
minus_qnty = minus_qnty - 1;
holder.qty.setText("" + minus_qnty);
String str=holder.sellprice.getText().toString();
Double sell_price= Double.parseDouble(str.replaceAll(getResources().getString(R.string.Rs), ""));
holder.singlerowprice.setText(getResources().getString(R.string.Rs)+" " + Double.parseDouble(holder.qty.getText().toString()) * sell_price);
prodetailarray.get(in).setQntity(String.valueOf(minus_qnty));
prodetailarray.get(in).setBaseprice("" + Double.parseDouble(base_price) * minus_qnty);
}
/*for calculate value after change if any change*/
Double add = 0.0;
Double pr = 0.0;
for (int i = 0; i < listView.getCount(); i++)
{
View v = listView.getAdapter().getView(i,null,listView);
if(v==null)
{
return;
}
TextView tvquan = (TextView) v.findViewById(R.id.txtquntty_prodetail);
TextView tvprice = (TextView) v.findViewById(R.id.txtsinglerow_price);
String str_qun=tvquan.getText().toString().trim();
Double c = Double.parseDouble(str_qun.replaceAll("KG", ""));
add = c + add;
String str = tvprice.getText().toString().trim();
Double p = Double.parseDouble(str.replaceAll(getResources().getString(R.string.Rs), ""));
pr = pr + p;
Log.d("listitemcount==", "tvquan==" + tvquan.getText().toString() + "add==" + add + "price" + pr);
totalamount.setText(getResources().getString(R.string.Rs) +" "+ pr);
// totalamount.setText(""+ pr);
}
}
else
{
}
}
});
if(!prodetailarray.get(listrowposition).getQntity().matches("[0-9]+"))
{
holder.qty.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View view)
{
index = (Integer) view.getTag();
Log.d("indexval==","index==="+index);
final Dialog dialog_item = new Dialog(Bill_details.this);
dialog_item.setContentView(R.layout.add_item_dialog);
dialog_item.getWindow().setLayout(AppBarLayout.LayoutParams.FILL_PARENT, AppBarLayout.LayoutParams.WRAP_CONTENT);
edt_enter_qntty = (EditText) dialog_item.findViewById(R.id.txtqntty_item_dialog);
TextView ok = (TextView) dialog_item.findViewById(R.id.txtok_item_dialog);
ok.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View view)
{
if(edt_enter_qntty.getText().toString().equals(""))
{
}
else
{
Double dialog_qntty= Double.parseDouble(edt_enter_qntty.getText().toString());
// PLUSMINUS = 100;
kg_qntty = dialog_qntty;
//this is for checking entered qunnt is not more than avail qntty
String whole_qnt=holder.whole_qntty.getText().toString();
String whole_qnt_replce= (whole_qnt.replaceAll("KG", ""));
whole_qnt_kg= Double.parseDouble(whole_qnt_replce);
Log.d("whole_qnt_kg==",""+whole_qnt_kg);
if(kg_qntty>whole_qnt_kg)
{
Toast.makeText(getApplicationContext(), getResources().getString(R.string.outofstock), Toast.LENGTH_LONG).show();
}
else
{
holder.qty.setText("" + kg_qntty+"KG");
prodetailarray.get(index).setQntity(String.valueOf(kg_qntty));
//remove all the text except price (integer value)
String str_qnty=prodetailarray.get(index).getQntity().toString();
Double qty= Double.parseDouble(str_qnty.replaceAll("KG", ""));
String str=holder.sellprice.getText().toString();
Double sell_price= Double.parseDouble(str.replaceAll(getResources().getString(R.string.Rs), ""));
Log.d("qty * sell_price==",""+qty+" "+sell_price);
holder.singlerowprice.setText(getResources().getString(R.string.Rs)+" " + qty * sell_price);
prodetailarray.get(index).setBaseprice("" + Double.parseDouble(base_price) * kg_qntty);
}
/*for calculate value after change if any change*/
Double add = 0.0;
Double pr = 0.0;
for (int i = 0;i < listView.getCount(); i++)
{
View v = listView.getAdapter().getView(i,null,listView);
if(v==null)
{
return;
}
TextView tvquan = (TextView) v.findViewById(R.id.txtquntty_prodetail);
TextView tvprice = (TextView) v.findViewById(R.id.txtsinglerow_price);
String str_quan=tvquan.getText().toString().trim();
Log.d("strqn",str_quan);
String c = (str_quan.replaceAll("KG", ""));
Log.d("strqn", "" + c);
add = Double.parseDouble(c) + add;
String str_pri=tvprice.getText().toString().trim();
Double p= Double.parseDouble(str_pri.replaceAll(getResources().getString(R.string.Rs), ""));
pr = pr + p;
Log.d("total_qntty", "tvquan==" + tvquan.getText().toString() + "add==" + add + "price" + pr);
// totalitem.setText("" + add+" Items");
totalamount.setText(getResources().getString(R.string.Rs) +" "+ pr);
}
}
dialog_item.dismiss();
}
});
dialog_item.show();
}
});
}
return convertView;
}
I have an issue.I have custom listView which has many child and also have another custom listview in it.All data which is display in both listView is coming from database.My Problem is that When I scroll My main ListView it stucks for a while and then scroll.I uploaded My all code here.
My Main Activity class:
public class TransactionListMonthWise<DisplayYear> extends TopParentActivity {
ListView statement;
ArrayList<DisplayMonth> status;
ArrayList<DisplayYear> yearstatus;
addBankTransactionList mAdapter;
TextView tvBankName, tvBalance, tvBankAccNoForHistory;
String monthname;
String monthName;
int yearName;
String bankname, amount, accno;
Date theDate;
String currencySymbl, cur_sym;
EPreferences epref;
String TotalBalance, BankBalance, finalTotalIncome;
Toolbar toolbarTransactionListMonthWise;
boolean loadingMore = false;
int itemsPerPage = 2;
DisplayMonth monthNameInAdapter;
int month;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_transaction_monthwise);
bindview();
init();
addListener();
}
private void init() {
epref = EPreferences.getInstance(TransactionListMonthWise.this);
getPrefData();
Intent intent = getIntent();
bankname = intent.getStringExtra("NAME");
tvBankName.setText(bankname);
TotalBalance = String.valueOf(intent.getDoubleExtra("BALANCE", 0.0));
BankBalance = new BigDecimal(TotalBalance).toPlainString();
DecimalFormat decimalFormatIncome = new DecimalFormat("0.#");
finalTotalIncome = decimalFormatIncome.format(Double
.valueOf(TotalBalance));
tvBalance.setText(currencySymbl
+ " "
+ String.format("%,.00f",
(double) Double.parseDouble(finalTotalIncome)));
// tvBalance.setText(amount + " " + currencySymbl);
Log.i("symbol", currencySymbl);
accno = intent.getStringExtra("ACCNO");
status = new ArrayList<DisplayMonth>();
yearstatus = new ArrayList<DisplayYear>();
tvBankAccNoForHistory.setText("xxxxx"
+ intent.getStringExtra("ACC_NUMBER"));
Utils.BANK_ACC_NUM = intent.getStringExtra("ACC_NUMBER");
Utils.BANK_NAME_DISP = bankname;
setSupportActionBar(toolbarTransactionListMonthWise);
this.toolbarTransactionListMonthWise
.setNavigationIcon(R.drawable.ic_arrow_back_white100);
getSupportActionBar().setTitle(bankname + " History");
}
private void bindview() {
toolbarTransactionListMonthWise = (Toolbar) findViewById(R.id.toolbarTransactionListMonthWise);
statement = (ListView) findViewById(R.id.list_transaction_view);
tvBankName = (TextView) findViewById(R.id.tvBankNameForHistory);
tvBalance = (TextView) findViewById(R.id.tvNetBalanceForHistory);
tvBankAccNoForHistory = (TextView) findViewById(R.id.tvBankAccNoForHistory);
}
private void addListener() {
statement.setOnScrollListener(new AbsListView.OnScrollListener() {
int mLastFirstVisibleItem;
boolean mIsScrollingUp;
#Override
public void onScrollStateChanged(AbsListView view, int scrollstate) {
}
#Override
public void onScroll(AbsListView view, int firstVisibleItem,
int visibleItemCount, int totalItemCount) {
int lastInScreen = firstVisibleItem + visibleItemCount;
if ((lastInScreen == totalItemCount)) {
new MailSender().execute();
}
}
});
}
#Override
public void onBackPressed() {
super.onBackPressed();
Intent intent = new Intent(TransactionListMonthWise.this,
BankList.class);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(intent);
}
private String getMonth(int month1) {
switch (month1) {
case 1:
monthname = "Jan";
break;
case 2:
monthname = "Feb";
break;
case 3:
monthname = "Mar";
break;
case 4:
monthname = "Apr";
break;
case 5:
monthname = "May";
break;
case 6:
monthname = "Jun";
break;
case 7:
monthname = "Jul";
break;
case 8:
monthname = "Aug";
break;
case 9:
monthname = "Sep";
break;
case 10:
monthname = "Oct";
break;
case 11:
monthname = "Nov";
break;
case 12:
monthname = "Dec";
break;
default:
break;
}
return monthname;
}
private int getYear(int years) {
switch (years) {
case 1:
years = 2011;
break;
case 2:
years = 2012;
break;
case 3:
years = 2013;
break;
case 4:
years = 2014;
break;
case 5:
years = 2015;
break;
case 6:
years = 2016;
break;
default:
break;
}
return years;
}
private void getPrefData() {
cur_sym = epref.getPreferencesStr(epref.KEY_CURRENCY, "India");
Log.d("vaaaaa", " == " + cur_sym);
if (cur_sym.equalsIgnoreCase("India")) {
currencySymbl = getResources().getString(R.string.India);
} else if (cur_sym.equalsIgnoreCase("US")) {
currencySymbl = getResources().getString(R.string.United_States);
} else if (cur_sym.equalsIgnoreCase("Japan")) {
currencySymbl = getResources().getString(R.string.Japan);
} else if (cur_sym.equalsIgnoreCase("England")) {
currencySymbl = getResources().getString(R.string.England_pound);
} else if (cur_sym.equalsIgnoreCase("Costa Rica")) {
currencySymbl = getResources().getString(R.string.Costa);
} else if (cur_sym.equalsIgnoreCase("UK")) {
currencySymbl = getResources().getString(R.string.United);
} else if (cur_sym.equalsIgnoreCase("Phillipines")) {
currencySymbl = getResources().getString(R.string.Philippines);
} else if (cur_sym.equalsIgnoreCase("Mangolia")) {
currencySymbl = getResources().getString(R.string.Macedonia);
} else if (cur_sym.equalsIgnoreCase("Australia")) {
currencySymbl = getResources().getString(R.string.Australia);
} else if (cur_sym.equalsIgnoreCase("Europ")) {
currencySymbl = getResources().getString(R.string.Euro);
}
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if (item.getItemId() == android.R.id.home) {
onBackPressed();
}
return super.onOptionsItemSelected(item);
}
public class MailSender extends AsyncTask<Void, Integer, Integer> {
Dialog progress;
#SuppressLint("ResourceAsColor")
#Override
protected void onPreExecute() {
super.onPreExecute();
progress = new Dialog(TransactionListMonthWise.this,
R.style.AppDialogExit);
progress.requestWindowFeature(Window.FEATURE_NO_TITLE);
progress.show();
progress.setContentView(R.layout.custom_loading_dialog);
TextView tv = (TextView) progress.findViewById(R.id.tv);
tv.setText("Mail is sending...");
progress.setCanceledOnTouchOutside(false);
progress.setCancelable(false);
}
#Override
protected Integer doInBackground(Void... params) {
final RelativeLayout footerView = (RelativeLayout) findViewById(R.id.loadItemsLayout_recyclerView);
Calendar cal = Calendar.getInstance();
month = cal.get(Calendar.MONTH) + 1;
// int year = cal.get(Calendar.YEAR) - 10;
int currentYear = cal.get(Calendar.YEAR);
Log.d("viewMonths", "month is" + month + " " + currentYear);
for (int j = month; j > 0; j--) {
monthNameInAdapter = new DisplayMonth();
monthName = getMonth(j);
monthNameInAdapter.setMonth(monthName);
status.add(monthNameInAdapter);
}
mAdapter = new addBankTransactionList(getApplicationContext(),
month, status, bankname, accno, currentYear, amount);
return 0;
}
#Override
protected void onPostExecute(Integer result) {
super.onPostExecute(result);
// progress.dismiss();
if (progress != null) {
progress.dismiss();
progress = null;
}
try {
statement.setAdapter(mAdapter);
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
Main Xml:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="#color/white"
android:fitsSystemWindows="true"
android:gravity="center"
android:orientation="vertical" >
<android.support.v7.widget.Toolbar
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="#+id/toolbarTransactionListMonthWise"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:background="?colorPrimary"
android:minHeight="?actionBarSize"
android:paddingRight="10dp"
app:popupTheme="#style/ThemeOverlay.AppCompat.Light"
app:theme="#style/ThemeOverlay.AppCompat.Dark.ActionBar" >
</android.support.v7.widget.Toolbar>
<android.support.v7.widget.CardView
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:card_view="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="70dp"
android:layout_marginLeft="4dp"
android:layout_marginRight="4dp"
card_view:cardCornerRadius="5dp"
card_view:cardUseCompatPadding="true" >
<RelativeLayout
android:id="#+id/rlBankNameAndBalance"
android:layout_width="fill_parent"
android:layout_height="match_parent"
android:layout_weight="1"
android:background="#color/green_100"
android:clickable="true"
android:gravity="right"
android:orientation="vertical"
android:paddingLeft="#dimen/main_list_data_disp_padding_left"
android:paddingRight="#dimen/main_list_data_disp_padding_right"
android:paddingTop="#dimen/main_list_data_disp_padding_top" >
<TextView
android:id="#+id/tvBankNameForHistory"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_toRightOf="#+id/iconId"
android:text="#string/BankBalance"
android:textColor="#color/gray_900"
android:textSize="#dimen/main_list_data_disp_text_size" />
<TextView
android:id="#+id/tvBankAccNoForHistory"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_below="#+id/tvBankNameForHistory"
android:text="#string/BankBalance"
android:textColor="#color/gray_500"
android:textSize="14sp" />
<TextView
android:id="#+id/tvNetBalanceForHistory"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:layout_alignParentTop="true"
android:textColor="#color/gray_900"
android:textSize="#dimen/main_list_data_disp_text_size" />
</RelativeLayout>
</android.support.v7.widget.CardView>
<ListView
android:id="#+id/list_transaction_view"
android:layout_width="match_parent"
android:layout_height="fill_parent"
android:layout_margin="2dp"
android:scrollbars="none" />
<include
android:id="#+id/loadItemsLayout_recyclerView"
android:layout_width="fill_parent"
android:layout_height="110dp"
android:layout_alignParentBottom="true"
layout="#layout/progress_layout"
android:visibility="gone" />
Main Adapter Class:
public class addBankTransactionList extends BaseAdapter {
// Activity activityCategory;
static ArrayList<DisplayMonth> monthName;
// ArrayList<DisplayYear> yearName;
ArrayList<Expense> expense;
ArrayList<Income> incomes, Arr;
#SuppressWarnings("rawtypes")
ArrayList<String> arrDateDebit, arrDateCredit;
ArrayList<Double> arrAmountDebit, arrAmountCredit;
Context contextAddBank;
int CurrentMonth;
String bankNameForMatch, months, allyear, SystemMonthInString, amount,
bankAccNoForMatch;
int monthname;
String currencySymbl, cur_sym;
String date = "", thirdYear;
String monthNameInString;
EPreferences epref;
ArrayList<Income> tempIncomeses = new ArrayList<Income>();
String dateIncome, dateExpense;
Double expenseAmount, incomeAmount;
DataBaseAdapter adapter;
// private String ;
int monthNameInStringExpense, monthNameInStringIncome;
int yr, year;
int monthsInIntIncome, dateInIntIncome, yearInIntIncome,
monthsInIntExpense;
String convertDate;
// private ArrayList<Income> tempincomes = new ArrayList<Income>();
List list;
Date date1;
String emptyExpenseAmount, emptyIncomeAmount;
FilterData data;
private String bankname, accno;
public static Boolean isScrolling = true;
public static class ViewHolder {
public TextView tvDate, tvIncomeMoney, tvExpenseMoney,
tvRecordnotFound, tvIncomeSymblIncomeDisp, tvTransactionType,
tvTransactionDate, tvTransactionAmount, tvMoneyCurrencyExpense,
tvMoneyCurrencyIncome;
ListView rvList;
}
public addBankTransactionList(Context mcontext, int month,
ArrayList<DisplayMonth> status, String bankname, String bankAccNo,
int year, String amt) {
super();
this.contextAddBank = mcontext;
monthName = status;
CurrentMonth = month;
bankNameForMatch = bankname;
bankAccNoForMatch = bankAccNo;
yr = year;
amount = amt;
}
public boolean setListViewHeightBasedOnItems(ListView listView) {
ListAdapter listAdapter = listView.getAdapter();
if (listAdapter != null) {
int numberOfItems = listAdapter.getCount();
Log.i("TotalRecord", numberOfItems + "");
int totalItemsHeight = 0;
for (int itemPos = 0; itemPos < numberOfItems; itemPos++) {
View item = listAdapter.getView(itemPos, null, listView);
item.measure(0, 0);
totalItemsHeight += item.getMeasuredHeight();
}
int totalDividersHeight = listView.getDividerHeight()
* (numberOfItems - 1);
ViewGroup.LayoutParams params = listView.getLayoutParams();
params.height = totalItemsHeight + totalDividersHeight;
listView.setLayoutParams(params);
listView.requestLayout();
listView.setClickable(false);
listView.setEnabled(false);
return true;
} else {
return false;
}
}
private void getPrefData() {
cur_sym = epref.getPreferencesStr(epref.KEY_CURRENCY, "India");
Log.d("vaaaaa", " == " + cur_sym);
if (cur_sym.equalsIgnoreCase("India")) {
currencySymbl = contextAddBank.getResources().getString(
R.string.India);
} else if (cur_sym.equalsIgnoreCase("US")) {
currencySymbl = contextAddBank.getResources().getString(
R.string.United_States);
} else if (cur_sym.equalsIgnoreCase("Japan")) {
currencySymbl = contextAddBank.getResources().getString(
R.string.Japan);
} else if (cur_sym.equalsIgnoreCase("England")) {
currencySymbl = contextAddBank.getResources().getString(
R.string.England_pound);
} else if (cur_sym.equalsIgnoreCase("Costa Rica")) {
currencySymbl = contextAddBank.getResources().getString(
R.string.Costa);
} else if (cur_sym.equalsIgnoreCase("UK")) {
currencySymbl = contextAddBank.getResources().getString(
R.string.United);
} else if (cur_sym.equalsIgnoreCase("Phillipines")) {
currencySymbl = contextAddBank.getResources().getString(
R.string.Philippines);
} else if (cur_sym.equalsIgnoreCase("Mangolia")) {
currencySymbl = contextAddBank.getResources().getString(
R.string.Macedonia);
} else if (cur_sym.equalsIgnoreCase("Australia")) {
currencySymbl = contextAddBank.getResources().getString(
R.string.Australia);
} else if (cur_sym.equalsIgnoreCase("Europ")) {
currencySymbl = contextAddBank.getResources().getString(
R.string.Euro);
}
}
private int getMonthName(String month1) {
switch (month1.toLowerCase().toString()) {
case "Jan":
monthname = 1;
break;
case "Feb":
monthname = 2;
break;
case "Mar":
monthname = 3;
break;
case "Apr":
monthname = 4;
break;
case "May":
monthname = 5;
break;
case "Jun":
monthname = 6;
break;
case "Jul":
monthname = 7;
break;
case "Aug":
monthname = 8;
break;
case "Sep":
monthname = 9;
break;
case "Oct":
monthname = 10;
break;
case "Nov":
monthname = 11;
break;
case "Dec":
monthname = 12;
break;
default:
break;
}
return monthname;
}
#Override
public int getCount() {
return monthName.size();
}
#Override
public Object getItem(int position) {
return position;
}
#Override
public long getItemId(int arg0) {
return 0;
}
#Override
public View getView(int position, View conView, ViewGroup parent) {
ViewHolder vh;
if (conView == null) {
conView = LayoutInflater.from(contextAddBank).inflate(
R.layout.transaction_list, null, false);
vh = new ViewHolder();
vh.tvDate = (TextView) conView.findViewById(R.id.tvDate);
vh.rvList = (ListView) conView
.findViewById(R.id.lvDisplayExpenseList);
vh.tvIncomeMoney = (TextView) conView
.findViewById(R.id.tvIncomeMoney);
vh.tvExpenseMoney = (TextView) conView
.findViewById(R.id.tvExpenseMoney);
vh.tvRecordnotFound = (TextView) conView
.findViewById(R.id.tvrecordnotFound);
vh.tvIncomeSymblIncomeDisp = (TextView) conView
.findViewById(R.id.tvIncomeSymblIncomeDisp);
vh.tvMoneyCurrencyExpense = (TextView) conView
.findViewById(R.id.tvMoneyCurrencyExpense);
vh.tvMoneyCurrencyIncome = (TextView) conView
.findViewById(R.id.tvMoneyCurrencyIncome);
adapter = new DataBaseAdapter(contextAddBank);
arrDateDebit = new ArrayList<String>();
arrAmountDebit = new ArrayList<Double>();
arrDateCredit = new ArrayList<String>();
arrAmountCredit = new ArrayList<Double>();
epref = EPreferences.getInstance(contextAddBank);
incomes = new ArrayList<Income>();
expense = new ArrayList<Expense>();
getPrefData();
vh.tvMoneyCurrencyExpense.setText(currencySymbl);
vh.tvMoneyCurrencyIncome.setText(currencySymbl);
adapter.open();
adapter.close();
conView.setTag(vh);
} else {
vh = (ViewHolder) conView.getTag();
}
expense.clear();
incomes.clear();
arrDateCredit.clear();
arrAmountCredit.clear();
arrDateDebit.clear();
arrAmountDebit.clear();
adapter.open();
// viewHolder.rvList.setAdapter(Adapter);
incomes = adapter.read_income();
expense = adapter.read_expense();
double totalExpense = 0.0;
double totalIncome = 0.0;
DisplayMonth month = monthName.get(position);
vh.tvDate.setText(month.getMonth() + " " + yr);
months = month.getMonth();
Log.d("tagNameAdapter",
"name is " + bankNameForMatch + ":::" + month.getMonth());
Log.d("expencesize", "size is " + expense.size());
// expense = adapter.read_expense_with_bankName(bankNameForMatch,
// bankAccNoForMatch);
if (expense.size() > 0) {
for (int l = 0; l < expense.size(); l++) {
Log.d("tagbankfil",
"" + bankNameForMatch + "=="
+ expense.get(l).getBankname() + " AND "
+ expense.get(l).getAccno() + "=="
+ bankAccNoForMatch);
if (bankNameForMatch.equals(expense.get(l).getBankname())
&& bankAccNoForMatch.substring(
bankAccNoForMatch.length() - 3)
.equalsIgnoreCase(
expense.get(l)
.getAccno()
.substring(
expense.get(l)
.getAccno()
.length() - 3))) {
dateExpense = expense.get(l).getDate();
expenseAmount = expense.get(l).getAmount();
Log.i("ExpenseAmount", expenseAmount + ":::::"
+ dateExpense);
Calendar calendar = Calendar.getInstance();
year = calendar.get(Calendar.YEAR);
StringTokenizer tokensIncome = new StringTokenizer(
dateExpense, "-");
String firstDate = tokensIncome.nextToken();
String secondMonth = tokensIncome.nextToken();
thirdYear = tokensIncome.nextToken();
monthsInIntExpense = Integer.parseInt(secondMonth);
int totalYear = Integer.parseInt(thirdYear);
Log.i("MonthNameExpense", totalYear + "");
Log.i("MonthSplitExpense", firstDate + " " + secondMonth
+ " " + thirdYear);
// for (int jmon = 0; jmon < expense.size(); jmon++) {
Log.i("loopTimes", "Check");
SimpleDateFormat sdfSource = new SimpleDateFormat(
"dd-MM-yyyy");
Date dateVal = null;
Log.i("axisbankdateval", dateVal + "");
try {
dateVal = sdfSource.parse(dateExpense);
} catch (ParseException e) {
e.printStackTrace();
}
SimpleDateFormat sdfDestination = new SimpleDateFormat(
"dd-MMM-yyyy");
convertDate = sdfDestination.format(dateVal);
String[] parts = convertDate.split("-");
String transactionMonth = parts[1];
String transactionYear = parts[2];
Log.i("allYear", year + " ");
monthNameInStringExpense = getMonthName(transactionMonth);
Log.i("finddate", convertDate + ":::" + transactionMonth
+ ":::" + monthNameInStringExpense + "::"
+ transactionYear);
Log.d("tagmonth", "" + month.getMonth() + " ::: "
+ transactionMonth + " ---- " + totalYear + "::::"
+ year);
if (month.getMonth().contains(transactionMonth)
&& totalYear == year) {
emptyExpenseAmount = vh.tvExpenseMoney.getText()
.toString();
Log.i("dateAmount", " " + expense.get(l).getAmount()
+ " " + expense.get(l).getDate());
arrDateDebit.add(expense.get(l).getDate());
arrAmountDebit.add(expense.get(l).getAmount());
totalExpense += expense.get(l).getAmount();
DecimalFormat decimalFormatExpense = new DecimalFormat(
"0.#");
String finalTotalExpense = decimalFormatExpense
.format(Double.valueOf(totalExpense));
String valTvExpenseAmt = new BigDecimal(
finalTotalExpense).toPlainString();
vh.tvExpenseMoney.setText(String.format("%,.00f",
(double) Double.parseDouble(valTvExpenseAmt))
+ " " + currencySymbl);
if (totalExpense == 0.0) {
vh.tvExpenseMoney.setText("0.0");
vh.tvMoneyCurrencyExpense.setText(currencySymbl);
} else {
if (vh.tvRecordnotFound.getVisibility() == View.VISIBLE) {
vh.tvRecordnotFound.setVisibility(View.GONE);
vh.tvMoneyCurrencyExpense
.setVisibility(View.INVISIBLE);
vh.tvExpenseMoney.setText(" " + totalExpense
+ " " + currencySymbl);
vh.tvMoneyCurrencyExpense
.setText(currencySymbl);
}
}
}
}
}
}
if (incomes.size() > 0) {
for (int j = 0; j < incomes.size(); j++) {
Log.d("tagbankfil",
"" + bankNameForMatch + "=="
+ incomes.get(j).getIncome_bankname() + " AND "
+ incomes.get(j).getIncome_accno() + "=="
+ bankAccNoForMatch);
if (bankNameForMatch
.equals(incomes.get(j).getIncome_bankname())
&& bankAccNoForMatch
.substring(bankAccNoForMatch.length() - 3)
.equalsIgnoreCase(
incomes.get(j)
.getIncome_accno()
.substring(
incomes.get(j)
.getIncome_accno()
.length() - 3))) {
dateIncome = incomes.get(j).getIncome_date();
incomeAmount = incomes.get(j).getIncome_amount();
Log.i("IncomeAmount", incomeAmount + ":::::" + dateIncome);
Calendar calendar = Calendar.getInstance();
year = calendar.get(Calendar.YEAR);
StringTokenizer tokensIncome = new StringTokenizer(
dateIncome, "-");
String firstDate = tokensIncome.nextToken();
String secondMonth = tokensIncome.nextToken();
thirdYear = tokensIncome.nextToken();
monthsInIntIncome = Integer.parseInt(thirdYear);
int totalYear = Integer.parseInt(thirdYear);
Log.i("MonthNameIncome", monthsInIntIncome + " " + ""
+ monthNameInStringIncome + " " + dateIncome + " "
+ incomes.size() + "" + totalYear);
Log.i("MonthSplitIncome", firstDate + " " + secondMonth
+ " " + thirdYear);
Log.i("loopTimes", "Check");
SimpleDateFormat sdfSource = new SimpleDateFormat(
"dd-MM-yyyy");
Date dateVal = null;
Log.i("axisbankdateval", dateVal + "");
try {
dateVal = sdfSource.parse(dateIncome);
} catch (ParseException e) {
e.printStackTrace();
}
SimpleDateFormat sdfDestination = new SimpleDateFormat(
"dd-MMM-yyyy");
convertDate = sdfDestination.format(dateVal);
String[] parts = convertDate.split("-");
String transactionMonth = parts[1];
String transactionYear = parts[2];
monthNameInStringIncome = getMonthName(transactionMonth);
Log.i("finddate", convertDate + "::" + monthname + "::"
+ monthNameInStringIncome);
if (month.getMonth().contains(transactionMonth)
&& totalYear == year) {
emptyIncomeAmount = vh.tvIncomeMoney.getText()
.toString();
arrDateCredit.add(incomes.get(j).getIncome_date());
arrAmountCredit.add(incomes.get(j).getIncome_amount());
totalIncome += incomes.get(j).getIncome_amount();
DecimalFormat decimalFormatIncome = new DecimalFormat(
"0.#");
String finalTotalIncome = decimalFormatIncome
.format(Double.valueOf(totalIncome));
String valTvIncomeAmt = new BigDecimal(finalTotalIncome)
.toPlainString();
vh.tvIncomeMoney.setText(String.format("%,.00f",
(double) Double.parseDouble(valTvIncomeAmt))
+ " ");
vh.tvMoneyCurrencyIncome.setText(currencySymbl);
if (totalIncome == 0.0) {
vh.tvIncomeMoney.setText("0.0");
vh.tvMoneyCurrencyIncome.setText(currencySymbl);
} else {
if (vh.tvRecordnotFound.getVisibility() == View.VISIBLE) {
vh.tvRecordnotFound.setVisibility(View.GONE);
vh.tvIncomeMoney.setText(" " + totalIncome
+ " " + currencySymbl);
}
}
}
}
}
Log.i("currentYear", year + "" + thirdYear);
}
CategoryList categoryListAdapter = new CategoryList(contextAddBank,
arrDateDebit, arrAmountDebit, arrDateCredit, arrAmountCredit);
vh.rvList.setAdapter(categoryListAdapter);
setListViewHeightBasedOnItems(vh.rvList);
vh.rvList.setScrollContainer(true);
categoryListAdapter.notifyDataSetChanged();
return conView;
}
}
Your application is sticking when you're scrolling down because you're doing all of that processing upon every move when you scroll. Every row is running through the statements of your getView method every single time it's brought back to the screen, phones don't have enough processing power for all of that. You need to separate all of that into a different class, and then load it into the adapter in a smaller data set so that all it has to do is display it. Basically, you're doing processing in the UI(Main) thread, which is bad.
Given how you also have nested listViews, changing to an expandedListView would also be a lot easier for you in the grand scheme of things, may do the job better. Here's a tutorial for it: https://www.youtube.com/watch?v=BkazaAeeW1Q
I am working on a android application with sqlite database that store lots of standard english texts that have uppercase and lowercase words and it shows on the app, we have a search that right now is case sensitive and scroll between them with cursor
How I can return search string case insensitive from sqlite
this is my code on database
public List<String> getSearchedParagraph(String p) {
String sectionId = "";
List<String> result = new ArrayList<String>();
String query = "SELECT Distinct(sectionId) FROM paragraph where txt Like '%"
+p+ "%'";
Cursor cursor = db.rawQuery(query, null);
if (cursor != null && cursor.getCount() > 0) {
cursor.moveToFirst();
while (!cursor.isAfterLast()) {
result.add(cursor.getString(0));
cursor.moveToNext();
}
}
return result;
}
i tested String query = "SELECT Distinct(sectionId) FROM paragraph where txt Like '%" +p+ "%' COLLATE NOCASE"; but still no change
UPDATE1 this is setWordSearch function:
public void setWordSearch(String str) {
wordSearch = str;
for (FragmentPage page : fragments) {
page.wordSearch = str;
}
notifyDataSetChanged();
}
UPDATE2 This is the FragmentPage:
public class FragmentPage extends Fragment {
VasiatClass v;
public String SectionId;
public List<VasiatClass> paragraph;
public String wordSearch;
private ScrollView sv;
static MediaPlayer player = new MediaPlayer();
View view;
private List<RelativeLayout> jtxtvwList = new ArrayList<RelativeLayout>();
RelativeLayout rl = null;
float position_x = 0, position_y = 0;
private int playingParagraphPosition;
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
this.SectionId = String.valueOf(getArguments().getInt("sectionId"));
this.wordSearch = getArguments().getString("wordSearch");
Log.i("FRAGMENTPAGE",
"sectionId is :"
+ String.valueOf(getArguments().getInt("sectionId")));
DataBaseHelper myDbHelper = new DataBaseHelper(this.getActivity());
myDbHelper = new DataBaseHelper(this.getActivity());
wordSearch = getArguments().getString("wordSearch");
try {
myDbHelper.createDataBase();
myDbHelper.openDataBase();
this.paragraph = myDbHelper.getParagraph(SectionId);
myDbHelper.close();
} catch (IOException ioe) {
throw new Error("Unable to create database");
}
};
public String getSection() {
return SectionId;
}
public FragmentPage() {
// TODO Auto-generated constructor stub
}
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_vasiatpage, container,
false);
this.view = view;
LinearLayout ll = (LinearLayout) view.findViewById(R.id.llId);
ll.setPadding(20, 20, 20, 20);
LinearLayout.LayoutParams linLayoutParam = new LinearLayout.LayoutParams(
LinearLayout.LayoutParams.FILL_PARENT,
LinearLayout.LayoutParams.WRAP_CONTENT);
linLayoutParam.setMargins(20, 20, 20, 20);
sv = (ScrollView) view.findViewById(R.id.scrollView1);
for (int i = 0; i <= paragraph.size() - 1; i++) {
final int j = i;
final RelativeLayout rel = new RelativeLayout(getActivity());
// Button b = new Button(getActivity());
// b.setBackgroundColor(Color.TRANSPARENT);
// b.setTextColor(Color.TRANSPARENT);
JustifiedTextView textView = new JustifiedTextView(getActivity());
/************************************/
textView.setOnTouchListener(new OnTouchListener() {
public final static int FINGER_RELEASED = 0;
public final static int FINGER_TOUCHED = 1;
public final static int FINGER_DRAGGING = 2;
public final static int FINGER_UNDEFINED = 3;
private int fingerState = FINGER_RELEASED;
#Override
public boolean onTouch(View arg0, MotionEvent arg1) {
int action = arg1.getAction();
boolean check = true;
switch (action) {
case MotionEvent.ACTION_DOWN:
position_x = arg1.getX();
position_y = arg1.getY();
Log.i("ACTIONS", "Ation down -- position_x:"
+ position_x + " ,position_Y" + position_y);
check = true;
if (fingerState == FINGER_RELEASED)
fingerState = FINGER_TOUCHED;
else
fingerState = FINGER_UNDEFINED;
break;
case MotionEvent.ACTION_MOVE:
if (fingerState == FINGER_TOUCHED
|| fingerState == FINGER_DRAGGING)
fingerState = FINGER_DRAGGING;
else
fingerState = FINGER_UNDEFINED;
check = false;
break;
case MotionEvent.ACTION_UP:
Log.i("ACTIONS",
"Ation up -- position_x:" + arg1.getX()
+ " ,position_Y" + arg1.getY());
if (Math.abs((arg1.getX() - position_x)) < 10
&& Math.abs((arg1.getY() - position_y)) < 10) {
List<String> audioList = new ArrayList<String>();
playingParagraphPosition = j;
((VasiatText) getActivity())
.playParagraph(paragraph.get(j)
.getFilename() + "_MP3.mp3", j,
FragmentPage.this);
if (rl != null) {
rl.setBackgroundColor(Color.TRANSPARENT);
}
rel.setBackgroundColor(Color.LTGRAY);
rl = rel;
}
break;
default:
fingerState = FINGER_UNDEFINED;
break;
}
return false;
}
});
/********************************************/
// textView.getSettings().setFixedFontFamily("Swissra Light.otf");
String str = paragraph.get(i).getTxt().toString();
int subStringStart = 0;
int startIndex = 0;
StringBuilder sb = new StringBuilder();
if (wordSearch != null && !wordSearch.equals("")) {
startIndex = str.indexOf(wordSearch);
while (startIndex != -1) {
sb.append(str.substring(subStringStart, startIndex)
+ "<span style=\"background-color:#ffff00\">"
+ str.substring(startIndex,
startIndex + wordSearch.length())
+ "</span>");
subStringStart = startIndex + wordSearch.length();
startIndex = str.indexOf(wordSearch, subStringStart);
}
sb.append(str.substring(subStringStart));
}
if (!sb.toString().equals("")) {
if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
textView.setText(sb.toString());
} else
textView.setTextNoJustify(sb.toString());
// b.setText(sb.toString());
} else {
if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
textView.setText(str);
} else
textView.setTextNoJustify(str);
// b.setText(str);
}
textView.setId(i);
textView.setTag(Integer.valueOf(paragraph.get(i).getId()));
rel.addView(textView);
jtxtvwList.add(rel);
ll.addView(rel);
}
return view;
}
thanks
as #CL mentioned, you can use Patterns,
just replace this code:
if (wordSearch != null && !wordSearch.equals("")) {
startIndex = str.indexOf(wordSearch);
while (startIndex != -1) {
sb.append(str.substring(subStringStart, startIndex)
+ "<span style=\"background-color:#ffff00\">"
+ str.substring(startIndex,
startIndex + wordSearch.length())
+ "</span>");
subStringStart = startIndex + wordSearch.length();
startIndex = str.indexOf(wordSearch, subStringStart);
}
sb.append(str.substring(subStringStart));
}
whit this:
Boolean wasFound;
if (wordSearch != null && !wordSearch.equals("")) {
Matcher subMatcher = Pattern.compile(Pattern.quote(wordSearch), Pattern.CASE_INSENSITIVE).matcher(str);
wasFound = subMatcher.find();
while (wasFound) {
startIndex = subMatcher.start();
sb.append(str.substring(subStringStart, startIndex)
+ "<span style=\"background-color:#ffff00\">"
+ str.substring(startIndex,
startIndex + wordSearch.length())
+ "</span>");
subStringStart = startIndex + wordSearch.length();
wasFound = subMatcher.find();
}
sb.append(str.substring(subStringStart));
}
I hope that this help you #n3tg33k ;)
You are using String.indexOf for searching. This function is case sensitive.
You need to search for the substring while ignoring case.
you can achieve it in this way....
public List<String> getSearchedParagraph(String p) {
p=p.toLowerCase();
String sectionId = "";
List<String> result = new ArrayList<String>();
String query = "SELECT Distinct(sectionId) FROM paragraph where LOWER(txt) Like '%"
+p+ "%'";
Cursor cursor = db.rawQuery(query, null);
if (cursor != null && cursor.getCount() > 0) {
cursor.moveToFirst();
while (!cursor.isAfterLast()) {
result.add(cursor.getString(0));
cursor.moveToNext();
}
}
return result;
}
I'm using Achartengine to create a Line Graph. My current month is showing however the second line, last month, isn't showing it. Here's the lass and logcat: So as you can see from the logcat my dates are correct and so is the count from the previous month. So why its not showing is beyond me.
Log Cat:
08-07 16:13:43.969: I/PROJECTCARUSO(11734): DEBUG startdate: 2013-07-01 enddate: 2013-07-31
08-07 16:13:43.969: I/PROJECTCARUSO(11734): count: 9
08-07 16:13:43.979: I/PROJECTCARUSO(11734): DEBUG startdate: 2013-08-01 enddate: 2013-08-31
Class:
public class TempHistoryFragment extends Fragment{
private GraphicalView mChartView;
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
if (container == null) {
return null;
}
Calendar cal = Calendar.getInstance();
Calendar cal2 = Calendar.getInstance();
SimpleDateFormat month_date = new SimpleDateFormat("MMMMMMMMM");
SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd",Locale.US);
String month_name = month_date.format(cal.getTime());
ArrayList<Integer> xArray = new ArrayList<Integer>();
ArrayList<Integer> yArray = new ArrayList<Integer>();
ArrayList<Integer> xArray2 = new ArrayList<Integer>();
ArrayList<Integer> yArray2 = new ArrayList<Integer>();
cal.add(Calendar.MONTH ,-1);
String prev_month_name = month_date.format(cal.getTime());
int daysInMonth = cal.getActualMaximum(Calendar.DAY_OF_MONTH);
//***********************************************//
// Our first data Last MONTH
//***********************************************//
//start date for cursor
//cal.add(Calendar.MONTH, -1);
cal.set(Calendar.DATE, 1);
String startdate = df.format(cal.getTime());
//end date
cal.set(Calendar.DATE, daysInMonth);
String enddate = df.format(cal.getTime());
Log.i("PROJECTCARUSO","DEBUG startdate: " + startdate + " enddate: " + enddate);
Cursor c = getActivity().getContentResolver().query(StatusProvider.CONTENT_URI_CHARTING, null, "? < " + StatusData.KEY_CHARTING_DATE + " AND ? > " + StatusData.KEY_CHARTING_DATE , new String[] {startdate, enddate}, null); //
c.moveToFirst();
Log.i("PROJECTCARUSO","count: " + c.getCount());
if (c.getCount()>0 && c!=null) {
while (c.isAfterLast() == false) {
if ((isNumeric(c.getString(c.getColumnIndex(StatusData.KEY_CHARTING_TEMPERATURE))))) {
java.util.Date date = null;
int day = 0;
//get date from database
String datetest = c.getString(c.getColumnIndex(StatusData.KEY_CHARTING_DATE));
//try to reformat to date.
try {
date = format.parse(datetest);
day = date.getDate();
} catch (java.text.ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
xArray.add(day);
}
c.moveToNext();
}
}
int[] x = new int[xArray.size()];
for (int i = 0; i < xArray.size(); i++) {
x[i] = xArray.get(i);
}
int[] y = new int[yArray.size()];
for (int i = 0; i < yArray.size(); i++) {
y[i] = yArray.get(i);
}
TimeSeries series = new TimeSeries(prev_month_name);
for( int i = 0; i < y.length; i++)
{
series.add(x[i], y[i]);
}
//***********************************************//
// Our second data THIS MONTH
//***********************************************//
//start date for cursor
cal2.set(Calendar.DATE, 1);
String startdate2 = df.format(cal2.getTime());
//end date
cal2.set(Calendar.DATE, daysInMonth);
String enddate2 = df.format(cal2.getTime());
Log.i("PROJECTCARUSO","DEBUG startdate: " + startdate2 + " enddate: " + enddate2);
Cursor c2 = getActivity().getContentResolver().query(StatusProvider.CONTENT_URI_CHARTING, null, "? < " + StatusData.KEY_CHARTING_DATE + " AND ? > " + StatusData.KEY_CHARTING_DATE , new String[] {startdate2, enddate2}, null); //
c2.moveToFirst();
if (c2.getCount()>0 && c2!=null) {
while (c2.isAfterLast() == false) {
if (isNumeric(c2.getString(c2.getColumnIndex(StatusData.KEY_CHARTING_TEMPERATURE)))){
yArray2.add(c2.getInt(c2.getColumnIndex(StatusData.KEY_CHARTING_TEMPERATURE)));
java.util.Date date = null;
int day = 0;
//get date from database
String datetest = c2.getString(c2.getColumnIndex(StatusData.KEY_CHARTING_DATE));
//try to reformat to date.
try {
date = format.parse(datetest);
day = date.getDate();
} catch (java.text.ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
xArray2.add(day);
}
c2.moveToNext();
}
}
int[] x2 = new int[xArray2.size()];
for (int i = 0; i < xArray2.size(); i++) {
x2[i] = xArray2.get(i);
}
int[] y2 = new int[yArray2.size()];
for (int i = 0; i < yArray2.size(); i++) {
y2[i] = yArray2.get(i);
}
TimeSeries series2 = new TimeSeries(month_name);
for( int i = 0; i < x2.length; i++)
{
series2.add(x2[i], y2[i]);
}
XYMultipleSeriesDataset dataset = new XYMultipleSeriesDataset();
dataset.addSeries(series);
dataset.addSeries(series2);
XYMultipleSeriesRenderer mRenderer = new XYMultipleSeriesRenderer(); // Holds a collection of XYSeriesRenderer and customizes the graph
XYSeriesRenderer renderer = new XYSeriesRenderer(); // This will be used to customize line 1
XYSeriesRenderer renderer2 = new XYSeriesRenderer(); // This will be used to customize line 2
mRenderer.addSeriesRenderer(renderer);
mRenderer.addSeriesRenderer(renderer2);
// Customization time for line 1!
renderer.setColor(getResources().getColor(R.color.complementary));
renderer.setPointStyle(PointStyle.SQUARE);
renderer.setFillPoints(true);
// Customization time for line 2!
renderer2.setColor(getResources().getColor(R.color.base));
renderer2.setPointStyle(PointStyle.DIAMOND);
renderer2.setFillPoints(true);
mChartView = ChartFactory.getLineChartView(getActivity(), dataset, mRenderer);
//Set Chart Title and labels
mRenderer.setChartTitle("Temperature Tracking");
mRenderer.setChartTitleTextSize(getResources().getDimension(R.dimen.largeText));
mRenderer.setLabelsColor(getResources().getColor(R.color.primaryTextDark));
//YAxis of Temp
mRenderer.setYTitle("Temperature", 0);
mRenderer.setYAxisMin(80, 0);
mRenderer.setYAxisMax(110, 0);
mRenderer.setYLabelsAlign(Align.CENTER);
mRenderer.setYLabelsColor(0, getResources().getColor(R.color.primaryTextDark));
//XAxis of month
mRenderer.setXLabels(20);
mRenderer.setXTitle(month_name);
mRenderer.setXAxisMin(1);
mRenderer.setXAxisMax(daysInMonth);
mRenderer.setXLabelsColor(getResources().getColor(R.color.primaryTextDark));
//Set the display
mRenderer.setMarginsColor(getResources().getColor(R.color.transparent));
mRenderer.setShowCustomTextGrid(true);
mRenderer.setAxisTitleTextSize(getResources().getDimension(R.dimen.mediumText));
mRenderer.setLabelsTextSize(getResources().getDimension(R.dimen.smallMediumText));
mRenderer.setPanEnabled(false, false);
mRenderer.setClickEnabled(false);
mRenderer.setZoomEnabled(false, false);
return mChartView;
}
#SuppressWarnings("unused")
public static boolean isNumeric(String str)
{
try
{
double d = Double.parseDouble(str);
}
catch(NumberFormatException nfe)
{
return false;
}
return true;
}
}
Oh and here are those colors:
<color name ="base">#51bbc2</color>
<color name ="complementary">#C25951</color>
Thanks #Dan you lead me to the solution. I went and logged all the points to make sure all the right values were getting placed in the right array and come to find out yArray.add(c.getInt(c.getColumnIndex(StatusData.KEY_CHARTING_TEMPERATURE))); somehow got deleted. So now it works! Yay!