Majid
Majid

Reputation: 230

Covert a code to class

Can any one help me to learn how to convert a code to a class so I can use it every where? for example I have this code How can I convert it to a separate class and use it in my diffrent activities?

I am new with java and really have problem with this..Thanks for your helps

public  String getInformationData(String mySQL){
    String information_text=null;
    try{
db = SQLiteDatabase.openDatabase(ClubCP.DbPath,null,SQLiteDatabase.CREATE_IF_NECESSARY);
        Cursor information = mDb.rawQuery(mySQL,null);
        int information1 = information.getColumnIndex("description");

        while (information.moveToNext()) {

        String columns = (String) information.getString(information1);


        information_text =  "<head><style>@font-face {font-family: 'verdana';src: url('file://"+ ClubCP.SDcardPath+ "Homa.ttf');}body {font-family: 'verdana';color:#ffffff;font-size:18px;padding:10px 10px 0 10px;}</style></head>"+"<html Content-Type: text/html charset=UTF-8;dir=\"rtl\"><body>"
                + "<p dir=\"rtl\"  align=\"justify\">"                
              + columns
               + "</p> "
              + "</body></html>";
    }
    } catch (Exception e) {
        Toast.makeText(callingActivity, e.getMessage(), 1).show();
        }

    return information_text;
    }

Finally I created my class..I added another method to it but when I call it I get FC ..Where is my mistake?

package co.tosca.persianpoem;

import java.io.File;

import android.app.Activity;
import android.content.Context;
import android.content.res.Resources;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.Toast;

public class persian_poem_class {
     private Context c = null;
     private  SQLiteDatabase Db=null;
     private Activity callingActivity;
     //private Resources res =null ;

public persian_poem_class(Context c,Activity a)
        {
            // Constructor 
            this.c = c;
            Db = SQLiteDatabase.openDatabase(ClubCP.DbPath, null, SQLiteDatabase.CREATE_IF_NECESSARY);
            callingActivity=a;
        }

public String getInformationData(String mySQL)
        {
            String information_text = null;

            try
            {

                Cursor information = Db.rawQuery(mySQL,null);
                int information1 = information.getColumnIndex("description");
                while (information.moveToNext()) 
                {
                    String columns = (String) information.getString(information1);
                    information_text =  "<head><style>@font-face {font-family: 'verdana';src: url('file://"+ ClubCP.SDcardPath+ "Homa.ttf');}body {font-family: 'verdana';color:#ffffff;font-size:18px;padding:10px 10px 0 10px;}</style></head>"+"<html Content-Type: text/html charset=UTF-8;dir=\"rtl\"><body>"
                            + "<p dir=\"rtl\"  align=\"justify\">"                
                          + columns
                           + "</p> "
                          + "</body></html>";
                }
            } 
            catch (Exception e) 
            {
                Toast.makeText(c, e.getMessage(), Toast.LENGTH_SHORT).show();
            }

            return information_text;
        }

public void Change_header(View v,String id){
            String path = ClubCP.SDcardPath + "/temp/"+id+"-header.jpg"; 
             Log.i("view binder", path);
           File imgFile = new File(path);
           ImageView img=(ImageView)v;
            if(imgFile.exists()){
                Bitmap myBitmap = BitmapFactory.decodeFile(imgFile.getAbsolutePath());                         
                img.setImageBitmap(myBitmap);

                 }
                      else    {                
                 img.setImageDrawable(callingActivity.getDrawable(R.drawable.music_album_header_vinyl));

                 }
        }

public Cursor getData(String mySQL){

    Cursor c = Db.rawQuery(mySQL, null);

    return c;

}
public void closeMyDb()
{
    if (Db != null)
        Db.close();
    else
        throw new NullPointerException("No database selected!");
}
}

I call secound method by this code

persian_poem_class main = new persian_poem_class(Book_list.this);
ImageView header=(ImageView)findViewById(R.id.img_header_book_list_activity);
main.Change_header(header, Peot_ID_for_db);

Again thanks for your time.. I fixed my class but now I have another problem with Change_header method..I get this error for getDrawable(R.drawable.music_album_header_vinyl) "getdrawable is undifined" I searched and I found problem is with scope but Cant fix it..I tried c.getDrawable but still have problementer code here

Upvotes: 0

Views: 140

Answers (3)

Ali
Ali

Reputation: 2042

Okay I made a simple class according your request but some section of your code is unclear to me like ClubCP.DbPath or ClubCP.SDcardPath that I think these are static variables.

Anyway to use this class you need to make new instance from myClass:

myClass mMyClass = new myClass(youractivity.this);
mMyClass.getInformationData("your query");
mMyClass.closeMyDb() // To close your current database

Edited as per comment:

import java.io.File;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.Toast;

public class myClass 
{
    private Context c = null;
    private SQLiteDatabase mDb;

    public myClass(Context c)
    {
        // Constructor 
        this.c = c;
        mDb = SQLiteDatabase.openDatabase(ClubCP.DbPath, null, SQLiteDatabase.CREATE_IF_NECESSARY);
    }

    public String getInformationData(String mySQL)
    {
        String information_text = null;

        try
        {
            Cursor information = mDb.rawQuery(mySQL,null);
            int information1 = information.getColumnIndex("description");
            while (information.moveToNext()) 
            {
                String columns = (String) information.getString(information1);
                information_text =  "<head><style>@font-face {font-family: 'verdana';src: url('file://"+ ClubCP.SDcardPath+ "Homa.ttf');}body {font-family: 'verdana';color:#ffffff;font-size:18px;padding:10px 10px 0 10px;}</style></head>"+"<html Content-Type: text/html charset=UTF-8;dir=\"rtl\"><body>"
                        + "<p dir=\"rtl\"  align=\"justify\">"                
                      + columns
                       + "</p> "
                      + "</body></html>";
            }
        } 
        catch (Exception e) 
        {
            Toast.makeText(c, e.getMessage(), Toast.LENGTH_SHORT).show();
        }

        return information_text;
    }

    public void Change_header(View v, String id)
    {
       String path = ClubCP.SDcardPath + "/temp/"+id+"-header.jpg"; 
       Log.i("view binder", path);
       File imgFile = new File(path);
       ImageView img = (ImageView) v;

       if(imgFile.exists())
       {
           Bitmap myBitmap = BitmapFactory.decodeFile(imgFile.getAbsolutePath());                         
           img.setImageBitmap(myBitmap);
       }
       else               
         img.setImageDrawable(c.getResources().getDrawable(R.drawable.music_album_header_vinyl));
    }

    public void closeMyDb()
    {
        if (mDb != null)
            mDb.close();
        else
            throw new NullPointerException("No database selected!");
    }
}

Upvotes: 2

Luke Taylor
Luke Taylor

Reputation: 9599

Simple create a new class by right clicking on your src folder and clicking create new class.

Once you've gone the through the process of naming your class, go and paste your current code into that class, which would be your public String getInformationData(String mySQL) method.

Once this has been done, create a reference to this class, be creating an object of this class in every class/activity you want to call String getInformationData(String mySQL) from.

YourClass foo =  new YourClass();
foo.getInformationData(string);

I hope this helps.

Upvotes: 1

drew moore
drew moore

Reputation: 32680

First, create a new class with a name that is descriptive of what it does (i.e. replace myClass with the name). Then, you create a constructor for this class by calling public myClass() WITHOUT a return type (this is how Java identifies it as a constructor. The constructor is what gets called every time the class runs, so simply paste your code in the body of the constructor, and it will get called every time you create a new object of the class.

  Class myClass {
       ...
       public myClass(){
          public  String getInformationData(String mySQL){
          String information_text=null;
          try{
              db = SQLiteDatabase.openDatabase ...
          ... rest of code...

    return information_text;
}

}
}

Welcome to object-oriented programming :)

Upvotes: 1

Related Questions