2013-03-05 3 views
-1

Я делаю одно приложение, которое считывает QR-код при ловле кода Qr моих scrren должны быть перемещены в другой класс, но он показывает исключения нулевого указателяКак перейти из класса в другой класс

мой код для CameraTestActivity.java является

/* 
* Basic no frills app which integrates the ZBar barcode scanner with 
* the camera. 
* 
* Created by lisah0 on 2012-02-24 
*/ 
package net.sourceforge.zbar.android.CameraTest; 

import net.sourceforge.zbar.Config; 
import net.sourceforge.zbar.Image; 
import net.sourceforge.zbar.ImageScanner; 
import net.sourceforge.zbar.Symbol; 
import net.sourceforge.zbar.SymbolSet; 
import android.app.Activity; 
import android.content.Context; 
import android.content.Intent; 
import android.content.pm.ActivityInfo; 
import android.hardware.Camera; 
import android.hardware.Camera.AutoFocusCallback; 
import android.hardware.Camera.PreviewCallback; 
import android.hardware.Camera.Size; 
import android.os.Bundle; 
import android.os.Handler; 
import android.view.View; 
import android.view.View.OnClickListener; 
import android.widget.Button; 
import android.widget.FrameLayout; 
import android.widget.TextView; 

public class CameraTestActivity extends Activity { 
private Camera mCamera; 
private CameraPreview mPreview; 
private Handler autoFocusHandler; 

TextView scanText; 
Button scanButton; 
Intent i; 
Context context; 

ImageScanner scanner; 

private boolean barcodeScanned = false; 
private boolean previewing = true; 

static { 
    System.loadLibrary("iconv"); 
} 

public void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 

    setContentView(R.layout.main); 

    setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT); 

    autoFocusHandler = new Handler(); 
    mCamera = getCameraInstance(); 

    /* Instance barcode scanner */ 
    scanner = new ImageScanner(); 
    scanner.setConfig(0, Config.X_DENSITY, 3); 
    scanner.setConfig(0, Config.Y_DENSITY, 3); 

    mPreview = new CameraPreview(this, mCamera, previewCb, autoFocusCB); 
    FrameLayout preview = (FrameLayout) findViewById(R.id.cameraPreview); 
    preview.addView(mPreview); 

    scanText = (TextView) findViewById(R.id.scanText); 

    scanButton = (Button) findViewById(R.id.ScanButton); 

    scanButton.setOnClickListener(new OnClickListener() { 
     public void onClick(View v) { 
      if (barcodeScanned) { 
       barcodeScanned = false; 
       scanText.setText("Scanning..."); 
       mCamera.setPreviewCallback(previewCb); 
       mCamera.startPreview(); 
       previewing = true; 
       mCamera.autoFocus(autoFocusCB); 
      } 
     } 
    }); 
} 

public void onPause() { 
    super.onPause(); 
    releaseCamera(); 
} 

/** A safe way to get an instance of the Camera object. */ 
public static Camera getCameraInstance() { 
    Camera c = null; 
    try { 
     c = Camera.open(); 
    } catch (Exception e) { 
    } 
    return c; 
} 

private void releaseCamera() { 
    if (mCamera != null) { 
     previewing = false; 
     mCamera.setPreviewCallback(null); 
     mCamera.release(); 
     mCamera = null; 
    } 
} 

private Runnable doAutoFocus = new Runnable() { 
    public void run() { 
     if (previewing) 
      mCamera.autoFocus(autoFocusCB); 
    } 
}; 

PreviewCallback previewCb = new PreviewCallback() { 
    public void onPreviewFrame(byte[] data, Camera camera) { 
     Camera.Parameters parameters = camera.getParameters(); 
     Size size = parameters.getPreviewSize(); 

     Image barcode = new Image(size.width, size.height, "Y800"); 
     barcode.setData(data); 

     int result = scanner.scanImage(barcode); 

     if (result != 0) { 
      previewing = false; 
      mCamera.setPreviewCallback(null); 
      mCamera.stopPreview(); 

      SymbolSet syms = scanner.getResults(); 
      for (Symbol sym : syms) { 
       scanText.setText("barcode result " + sym.getData()); 
       barcodeScanned = true; 
       i = new Intent(context, beginmove.class); 
       startActivity(i); 

      } 

     } 


    } 
}; 



// Mimic continuous auto-focusing 
AutoFocusCallback autoFocusCB = new AutoFocusCallback() { 
    public void onAutoFocus(boolean success, Camera camera) { 
     autoFocusHandler.postDelayed(doAutoFocus, 1000); 
    } 
}; 
} 


CameraPreview. java 


/* 
* Barebones implementation of displaying camera preview. 
* 
* Created by lisah0 on 2012-02-24 
*/ 
package net.sourceforge.zbar.android.CameraTest; 

import java.io.IOException; 

import android.app.Activity; 
import android.os.Bundle; 

import android.util.Log; 

import android.view.View; 
import android.view.Surface; 
import android.view.SurfaceView; 
import android.view.SurfaceHolder; 

import android.content.Context; 

import android.hardware.Camera; 
import android.hardware.Camera.PreviewCallback; 
import android.hardware.Camera.AutoFocusCallback; 
import android.hardware.Camera.Parameters; 

/** A basic Camera preview class */ 
public class CameraPreview extends SurfaceView implements SurfaceHolder.Callback { 
private SurfaceHolder mHolder; 
private Camera mCamera; 
private PreviewCallback previewCallback; 
private AutoFocusCallback autoFocusCallback; 

public CameraPreview(Context context, Camera camera, 
        PreviewCallback previewCb, 
        AutoFocusCallback autoFocusCb) { 
    super(context); 
    mCamera = camera; 
    previewCallback = previewCb; 
    autoFocusCallback = autoFocusCb; 

    /* 
    * Set camera to continuous focus if supported, otherwise use 
    * software auto-focus. Only works for API level >=9. 
    */ 
    /* 
    Camera.Parameters parameters = camera.getParameters(); 
    for (String f : parameters.getSupportedFocusModes()) { 
     if (f == Parameters.FOCUS_MODE_CONTINUOUS_PICTURE) { 
      mCamera.setFocusMode(Parameters.FOCUS_MODE_CONTINUOUS_PICTURE); 
      autoFocusCallback = null; 
      break; 
     } 
    } 
    */ 

    // Install a SurfaceHolder.Callback so we get notified when the 
    // underlying surface is created and destroyed. 
    mHolder = getHolder(); 
    mHolder.addCallback(this); 

    // deprecated setting, but required on Android versions prior to 3.0 
    mHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS); 
} 

public void surfaceCreated(SurfaceHolder holder) { 
    // The Surface has been created, now tell the camera where to draw the preview. 
    try { 
     mCamera.setPreviewDisplay(holder); 
    } catch (IOException e) { 
     Log.d("DBG", "Error setting camera preview: " + e.getMessage()); 
    } 
} 

public void surfaceDestroyed(SurfaceHolder holder) { 
    // Camera preview released in activity 
} 

public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) { 
    /* 
    * If your preview can change or rotate, take care of those events here. 
    * Make sure to stop the preview before resizing or reformatting it. 
    */ 
    if (mHolder.getSurface() == null){ 
     // preview surface does not exist 
     return; 
    } 

    // stop preview before making changes 
    try { 
     mCamera.stopPreview(); 
    } catch (Exception e){ 
     // ignore: tried to stop a non-existent preview 
    } 

    try { 
     // Hard code camera surface rotation 90 degs to match Activity view in portrait 
     mCamera.setDisplayOrientation(90); 

     mCamera.setPreviewDisplay(mHolder); 
     mCamera.setPreviewCallback(previewCallback); 
     mCamera.startPreview(); 
     mCamera.autoFocus(autoFocusCallback); 
    } catch (Exception e){ 
     Log.d("DBG", "Error starting camera preview: " + e.getMessage()); 
    } 
} 
} 

Теперь я хочу, чтобы перейти к классу abc.java после сканирования и получения данных, как я должен пойти туда

+3

много кода, вопрос, который не приемлем, и не хватает терминов, необходимых для понимания ... Я бы сказал, что научиться концепции объектно-ориентированного программирования. – ppeterka

+0

Вы упомянули свою вторую активность в вашем файле манифеста? – itsrajesh4uguys

+1

, на какой линии вы получаете исключение. Можете ли вы отправить сообщение о трассировке стека? – Pratik

ответ

0

Class2 cls2 = новый Class2(); cls2.UpdateEmployee();

определяют в вашем Class1

+1

вы можете мне рассказать, как это сделать, поскольку я новичок в android, спасибо –

+0

см. Отредактированный код –

+0

поместите класс CameraPreview внутри файла CameraTestActivity.java в конец. -> удалить общедоступное ключевое слово CameraPreview –

0
i have done same thing here 
public class CategoryList extends Activity implements OnItemClickListener, OnClickListener { 

    // All static variables 
    static final String categoryURL = "api"; 

    // XML node keys 
    static final String KEY_GATEGORY= "Category"; 

    static final String KEY_CAT_ID = "cat_id"; 
    static final String KEY_CAT_NAME = "cat_name"; 
    String msg=""; 
    DatabaseHelper dbHelper; 
    TextView tvmsg; 
    EditText etCategoryName; 
    Button btnEdit,btnAdd; 
    ListView lvCategory; 
    ArrayList<Category> categoryList; 
    CategoryAdapterHelper ca; 
    Cursor records; 
    Dialog dialog; 
    Document doc; 
    XMLParser parser; 
    int flag=0; 

    @Override 
    public void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.category); 
     initComponant(); 
     //  setDatabase(); 
     (new AsyncTaskExample()).execute(""); 

    } 
    private class AsyncTaskExample extends AsyncTask<String, Void, String> { 
     // private String Content; 
     private ProgressDialog Dialog; 
     String response = ""; 

     @Override 
     protected void onPreExecute() { 
      Dialog = new ProgressDialog(CategoryList.this); 
      Dialog.requestWindowFeature(Window.FEATURE_NO_TITLE); 
      Dialog.setMessage("Loading android tutorial..."); 
      Dialog.setCancelable(false); 
      Dialog.show(); 

     } 
     @Override 
     protected String doInBackground(String... urls) { 

      try { 
       doc = parser.getXmlFromUrl(categoryURL); 
      } catch (SAXException e) { 
       e.printStackTrace(); 
      } 
      if(doc!= null){ 

       NodeList ner1=doc.getElementsByTagName(KEY_GATEGORY); 
       for (int j = 0; j < ner1.getLength(); j++) 
       { 
        Element e1 = (Element) ner1.item(j); 
        int id=Integer.parseInt(parser.getValue(e1,KEY_CAT_ID)); 
        String name=parser.getValue(e1,KEY_CAT_NAME); 
        Cursor c=dbHelper.selectRecord(true,id); 
        if(c.getCount()==0) 
         dbHelper.inserRecord(id,name); 
       } 

      } 
      else{ 
       Toast.makeText(CategoryList.this, "Sorry Unable to retrive data. Please try again later", Toast.LENGTH_LONG).show(); 
      } 

      return response; 
     } 
     @Override 
     protected void onPostExecute(String result) { 
      Dialog.dismiss(); 
      displayCategory(); 

     } 
    } 
    private void initComponant() { 
     // TODO Auto-generated method stub 
     categoryList= new ArrayList<Category>(); 
     lvCategory=(ListView)findViewById(R.id.Category_listCategory); 
     lvCategory.setOnItemClickListener(this); 

     btnAdd=(Button)findViewById(R.id.Category_btnAdd); 
     btnAdd.setOnClickListener(this); 
     btnEdit=(Button)findViewById(R.id.Category_btnEdit); 
     btnEdit.setOnClickListener(this); 
     dialog= new Dialog(CategoryList.this); 
     dialog.setContentView(R.layout.customdialog); 
     dialog.setTitle("Navigation Application"); 
     dbHelper=new DatabaseHelper(this); 
     parser = new XMLParser(); 
     doc = null; 

    } 

    private void displayCategory() { 
     // TODO Auto-generated method stub 
     lvCategory.setAdapter(null); 
     categoryList= new ArrayList<Category>(); 
     try 
     { 
      records=dbHelper.selectRecord(); 
      startManagingCursor(records); 
      if(records.getCount()>0) 
      { 
       btnEdit.setEnabled(true); 
       records.moveToFirst(); 
       while(!records.isAfterLast()) 
       { 
        categoryList.add(new Category(records.getInt(records.getColumnIndex("_categoryid")),records.getString(records.getColumnIndex("name")))); 
        records.moveToNext(); 
       } 
       ca=new CategoryAdapterHelper(this, categoryList,flag); 
       lvCategory.setAdapter(ca); 
      } 
      else 
      { 
       btnEdit.setEnabled(false); 
       new DialogDisplay().showDialog(dialog,"Game Category Not Define Yet.!"); 
      } 
     } 
     catch (Exception e) { 
      // TODO: handle exception 
     } 
    } 
    @Override 
    protected void onResume() { 
     // TODO Auto-generated method stub 
     super.onResume(); 
     displayCategory(); 
    } 
    @Override 
    public void onClick(View v) { 
     // TODO Auto-generated method stub 
     switch(v.getId()) 
     { 
     case R.id.Category_btnAdd: 
      Intent newCategory=new Intent(CategoryList.this,NewCategory.class); 
      startActivity(newCategory); 
      break; 
     case R.id.Category_btnEdit: 
      if(btnEdit.getText().toString().equals("Edit")) 
      { 
       flag=1; 
       btnEdit.setText("Done"); 
      } 
      else 
      { 
       flag=0; 
       btnEdit.setText("Edit"); 
      } 
      displayCategory(); 
      break; 
     } 

    } 
    class CategoryAdapterHelper extends BaseAdapter { 

     Context context; 
     int flag; 
     public ArrayList<Category> categoryList; 
     public CategoryAdapterHelper(Context c,ArrayList<Category> categoryList,int flag) { 
      // TODO Auto-generated constructor stub 
      context=c; 
      this.categoryList=categoryList; 
      this.flag=flag; 
     } 
     @Override 
     public int getCount() { 
      // TODO Auto-generated method stub 
      return categoryList.size(); 
     } 

     @Override 
     public Object getItem(int position) { 
      // TODO Auto-generated method stub 
      return null; 
     } 

     @Override 
     public long getItemId(int position) { 
      // TODO Auto-generated method stub 
      Category category=categoryList.get(position); 
      return category.id; 
     } 

     @Override 
     public View getView(int position, View convertView, ViewGroup parent) { 
      // TODO Auto-generated method stub 
      View view = convertView; 
      if (view == null) { 
       LayoutInflater vi= LayoutInflater.from(context); 
       view = vi.inflate(R.layout.category_detail,null); 
      } 
      Category category= categoryList.get(position); 
      if (category!= null) 
      { 
       TextView name = (TextView) view.findViewById(R.id.Category_detail_name); 
       final ImageView image=(ImageView)view.findViewById(R.id.Category_detail_imageView1); 
       if (name != null) 
       { 
        name.setText(category.categoryName); 
        if(flag==1) 
        { 
         image.setBackgroundResource(R.drawable.delete); 
         image.setTag(position); 
         image.setOnClickListener(new OnClickListener() { 

          @Override 
          public void onClick(View v) 
          {// TODO Auto-generated method stub 
           final int id=(int)getItemId(Integer.parseInt(image.getTag().toString())); 
           final AlertDialog.Builder dlgAlert = new AlertDialog.Builder(context); 
           dlgAlert.setMessage("Do you want to delete it?\nIt will deleted all the Games..!"); 
           dlgAlert.setTitle("Nevigation Application"); 
           dlgAlert.setPositiveButton("Delete",new DialogInterface.OnClickListener() 
           { 

            @Override 
            public void onClick(DialogInterface dialog, 
              int which) { 
             // TODO Auto-generated method stub 
             DatabaseHelper dbHelper=new DatabaseHelper(context); 
             dbHelper.deleteRecord("category", id); 
             displayCategory(); 
            } 

           }); 
           dlgAlert.setNegativeButton("cancel",new DialogInterface.OnClickListener() 
           { 

            @Override 
            public void onClick(DialogInterface dialog, 
              int which) { 
             // TODO Auto-generated method stub 
             dialog.dismiss(); 
            } 

           }); 
           dlgAlert.show(); 
          } 
         }); 
        } 
       } 
      } 
      return view; 
     } 

    } 
    @Override 
    public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) { 
     // TODO Auto-generated method stub 

     if(btnEdit.getText().toString().equals("Edit")) 
     { 
      Category category=categoryList.get(arg2); 
      Toast.makeText(CategoryList.this,""+category.id,Toast.LENGTH_SHORT).show(); 
      Intent gameIntent=new Intent(CategoryList.this,GameList.class); 
      gameIntent.putExtra("categoryid",category.id); 
      gameIntent.putExtra("categoryname", category.categoryName); 
      startActivity(gameIntent); 
     } 
    } 

} 
Смежные вопросы