2

The code is to get contacts list. But for one error. Pleas help me resolve. The mContext on line 42 returns and error "cannot make a static reference to the non-static method getapplicationcontext() from the type contextwrapper".

package com.example.demo;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.res.AssetFileDescriptor;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.ContactsContract;
import android.widget.ImageButton;

import android.util.Log;
import android.view.View;
  import android.view.View.OnClickListener;

public class MainActivity extends Activity {

ImageButton imageButton;
Context mContext =  getApplicationContext();
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    addListenerOnButton();
    data();
    getVcardString();
}
public static void getVcardString() {   


    String path = null;     
    String vfile = null;; 
     vfile = "Contacts.vcf"; 

    Cursor phones =              mContext.getContentResolver(). query(ContactsContract.     CommonDataKinds.Phone.CONTENT_URI, null,null, null, null);

    phones.moveToFirst();
    Log.i("Number of contacts", "cursorCount" +phones.getCount());  
    for(int i =0;i<phones.getCount();i++)   {       

         String lookupKey = phones.getString(phones.getColumnIndex(ContactsContract.Contacts.LOOKUP_KEY));
         Log.i("lookupKey", " " +lookupKey);
         Uri uri = Uri.withAppendedPath(ContactsContract.Contacts.CONTENT_VCARD_URI, lookupKey);
         AssetFileDescriptor fd;

         try  {
             fd = mContext.getContentResolver().openAssetFileDescriptor(uri, "r");
             FileInputStream fis = fd.createInputStream();
             byte[] buf = new byte[(int) fd.getDeclaredLength()];
             fis.read(buf);
             String VCard = new String(buf);          

             path = Environment.getExternalStorageDirectory().toString() +    File.separator + vfile;
             FileOutputStream mFileOutputStream = new FileOutputStream(path, true);
             mFileOutputStream.write(VCard.toString().getBytes());    

             phones.moveToNext();               

             File filevcf = new File(path);
             Log.i("file", "file" +filevcf);

         }catch(Exception e1) {
             e1.printStackTrace();  
         }
    }       
    Log.i("TAG", "No Contacts in Your Phone");          
}

protected void data() {             
    File filelocation = filevcf ;     
    Intent sharingIntent = new Intent(Intent.ACTION_SEND);
    sharingIntent.setType("vnd.android.cursor.dir/email");      
    sharingIntent.setType("application/x-vcard");       
    sharingIntent.putExtra(Intent.EXTRA_EMAIL, "mail@gmail.com" );       sharingIntent.putExtra(Intent.EXTRA_STREAM,Uri.parse("file://"+filelocation.getAbsolutePath()));
    startActivity(Intent.createChooser(sharingIntent, "Send email"));            
 }  

public void addListenerOnButton() {
    final Context context =   getApplicationContext();


    imageButton = (ImageButton) findViewById(R.id.imageButton1);

    imageButton.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View arg0) {


            Intent intent1 = new Intent(context, secondjav.class);
                        startActivity(intent1);   


        }

    });

  }

}
KiKMak
  • 828
  • 7
  • 27
AisneT
  • 173
  • 11

3 Answers3

0

Problem

This error means you are trying to access mContext, which is an instance field, in getVcardString(), which is a static method (thus NOT depending on an instance).

Note: As pointed out by @KiKMak42, I'm assuming here that the error you get is for mContext now, and not the getApplicationContext() method anymore.

Solution

You can do one of these 2 things:

  • Make this method non-static by removing the static keyword. If you do this, then an instance of this class will be needed to call this method, so mContext will exist.
  • Add the context as a parameter of the method (and do not reference the instance field mContext anymore)

To complete the answer, in any other context (no pun intended) you could technically also make the mContext field static (depending on the use you have of it). However, it's rarely the best option, and you clearly DON'T want to do that here. And you'll never want to do that for any Context in Android.

Joffrey
  • 32,348
  • 6
  • 68
  • 100
  • I think you have misunderstood the error, it says cannot make a static reference to the non-static method getapplicationcontext(). – KiKMak Apr 08 '14 at 08:39
  • Line 42 is that `mContext`, the wording of the error is weird indeed, but this reference will break anyway at this point. The OP probably used to get the error you mention, copy-pasted the error message, then moved the method reference to `mContext`'s initialization. Which will cause another error message, which I'm replying to. – Joffrey Apr 08 '14 at 08:42
0

if you really need that your method "getVcardString()" remains static, then you should do something like this: create new class for your application that extend android.app.Application

public class MyApplication extends Application {
   static Context appContext;

   public MyApplication() {
       super();
   }

   @Override
   public void onCreate() {
      super.onCreate();   

      appContext = getApplicationContext();
   }

   public static Context getContext() {
       return appContext;
   }
}

add this attribute in your manifest to application tag:

android:name=".MyApplication"

and in your getVcardString() method instead use of mContext use this static method of MyApplication Class:

MyApplication.getContext()

by this way you make application context accessible every where in your application.

-2

Remove final from

final Context context =   getApplicationContext();
KiKMak
  • 828
  • 7
  • 27