Android - 将数据从Activity类传递给Adapter类

时间:2016-05-11 18:45:52

标签: android android-intent adapter

我有3个类:LoginActivity,MapsActivity和MatchAdapter

前两个扩展了AppCompactActivity,最后一个是ArrayAdapter。 当我登录时(如果正确,在mySQLiteDB上匹配)我曾经获得当前用户的ID_contact并以这样的方式将其传递给MapsActivity:

登录我的LoginActivity:

String contact=databaseHelper.searchID_Contact(username,password);
Intent intent=new Intent(LoginActivity.this,MapsActivity.class);

            intent.putExtra("ID_CONTACT",contact);
            startActivity(intent);

在MapsActivity上,我可以通过以下方式轻松检索此数据:

public  String getId_contact(String conct){

    return conct;
}

 @Override
public void onMapReady(GoogleMap googleMap) {

String id_contact1=getIntent().getStringExtra("ID_CONTACT");
    String contact=getId_contact(id_contact1);
    Toast.makeText(MapsActivity.this, contact, Toast.LENGTH_LONG).show();
}

直到现在一切正常,它显示当前用户的ID。 我的问题是将这些数据(意图我不知道如何)传递给另一个名为MatchAdapter的类,它扩展了ArrayAdapter。

我在MapsActivity上尝试过这种方式:

public class MapsActivity extends AppCompatActivity implements ...{

public  String getId_contact(){

        String contact=getIntent().getStringExtra("ID_CONTACT");


        return contact;
    }

所以在MatchAdaper尝试检索这种方式:

MapsActivity mapsActivity=new MapsActivity();
String text=mapsActivity.getId_contact().toString();

但没有..我得到了NULLPOINTEREXCEPTION ......有人能帮助我吗?

4 个答案:

答案 0 :(得分:0)

您可以通过以下方式从适配器访问活动方法,从适配器的构造函数或任何您想要的地方调用此方法。

def compare
  nih_pub = NihPublication.where(user: current_user).all
  pubmed_pub = Publication.where(user: current_user).all

  nih_pub.each{ |nih|
    pubmed_pub.each { |pubmed|
      # Cast those strings to integers so you're comparing apples to apples.
      if nih.pubyear == pubmed.publication_year.to_i and nih.pmid == pubmed.pubmed_id.to_i
        nih.match = true
        nih.save!
      end
    }
  }

  @missing = nih_pub.where(match: false)
end

答案 1 :(得分:0)

当您创建MapsActivity的新实例时,这与调用startActivity()时获得的Activity实例不同。这基本上就是为什么你有一个空指针异常。

更重要的是,您永远不应该使用“new”手动创建Activity实例。通常,系统会通过startActivity()等机制为您创建Activity对象,这就是您应该如何获取它们。

Himanshu的建议可行,如果您的活动恰好是“托管”您的适配器,但这并不总能保证。更好的方法是直接将ID传递给MatchAdapter,无论是在构造函数中还是作为直接setter函数。至少,您应该执行“instanceof”检查以确保您的适配器上下文实际上是MapsActivity类型。

答案 2 :(得分:0)

那是我的MatchAdapter`包vincenzo.futsal4you;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import java.util.ArrayList;
import java.util.List;
import java.util.regex.MatchResult;


public class MatchAdapter extends ArrayAdapter{

    List list=new ArrayList();




    String text1=null;




    MatchAdapter matchAdapter;
    static String id_contatto3="";
    String fatto3="";
    Player player=new Player();




    public MatchAdapter(Context context, int resource) {
        super(context, resource);
    }

    public void add(Match object) {
        list.add(object);
        super.add(object);
    }

    @Override
    public int getCount() {
        return super.getCount();
    }

    @Override
    public Object getItem(int position) {
        return super.getItem(position);
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {

        View row=convertView;
        final Context context = null;
        final MatchHolder matchHolder;
        final String cc=null;



        if (row==null){


            LayoutInflater layoutInflater=(LayoutInflater)this.getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            row=layoutInflater.inflate(R.layout.display_match_row,parent,false);
            matchHolder=new MatchHolder();

            matchHolder.id_match=(TextView)row.findViewById(R.id.id_partita);
            matchHolder.id_contact=(TextView)row.findViewById(R.id.id_contatto);
            matchHolder.nome_partita=(TextView)row.findViewById(R.id.nome_partita);
            matchHolder.citta=(TextView)row.findViewById(R.id.citta);
            matchHolder.indirizzo=(TextView)row.findViewById(R.id.indirizzo);
            matchHolder.data=(TextView)row.findViewById(R.id.data);
            matchHolder.ora=(TextView)row.findViewById(R.id.ora);
//            matchHolder.id_contact=row.findViewById()
            matchHolder.join_us = (Button) row.findViewById(R.id.join_us);


            row.setTag(matchHolder);

        }
        else {
            matchHolder=(MatchHolder)row.getTag();
        }

        final Match match=(Match)getItem(position);

//        matchHolder.id_contact.setText(mapsActivity.getId_partita().toString());
        matchHolder.id_match.setText(match.getId().toString());
        matchHolder.nome_partita.setText(match.getName().toString());
        matchHolder.citta.setText(match.getCitta().toString());
        matchHolder.indirizzo.setText(match.getIndirizzo().toString());
        matchHolder.data.setText(match.getData().toString());
        matchHolder.ora.setText(match.getOra().toString());

//        assert ((MapsActivity) context) != null;
//        ((MapsActivity) context).getId_partita();

//        final String contact=matchHolder.getId_contatto();


        Log.e("BOOOOOO", matchHolder.getId_contatto2());
        final String fatto=matchHolder.getId_contatto2();
        fatto3=matchHolder.getId_contatto2();




        matchHolder.join_us.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
//
                String fatto2=matchHolder.getId_contatto2();
//                final String text3=mapsActivity.getId_partita(cc).toString();

                RelativeLayout rl = (RelativeLayout) v.getParent();
                RelativeLayout r2 = (RelativeLayout) v.getParent();
//                TextView tv = (TextView)rl.findViewById(R.id.nome_partita);
                TextView tv = (TextView) rl.findViewById(R.id.id_partita);
                TextView tv2 = (TextView) r2.findViewById(R.id.id_contatto);

                String id_partita = tv.getText().toString();
                String text2 = tv2.getText().toString();



                Toast.makeText(getContext(), id_partita, Toast.LENGTH_SHORT).show();
//                Toast.makeText(getContext(), matchHolder.setId_contatto(contact), Toast.LENGTH_SHORT).show();
                Toast.makeText(getContext(),matchHolder.getId_contatto2(),Toast.LENGTH_SHORT).show();


                player.setId_contatto(fatto3);
                player.setId_partita(id_partita);
//                databaseHelper=new DatabaseHelper(context);
//                databaseHelper.insertPlayer2(player);

                ((MapsActivity)context).getJoinPlayer(player);

                Toast pass1=Toast.makeText(getContext(), "One Row JOIN US created !", Toast.LENGTH_SHORT);
                pass1.show();


            }
        });

        return row;
    }

     static class MatchHolder{
        TextView id_match,nome_partita,citta,indirizzo,data,ora,id_contact;
        Button join_us;

        public MatchHolder(){}

        public String getId_contatto(String id_contatto) {
            return id_contatto;
        }
        public String getId_contatto2() {
            return id_contatto3;
        }

        public void setId_contatto(String id_contatto) {
            id_contatto3 = id_contatto;
        }


        public MatchHolder(String id_contatto){
            id_contatto3=id_contatto;

        }


    }
}

`所以问题是我在一个静态(内部)类(MatchHolder)中声明了一个String(id_contatto3)。将它解释为MatchAdapter我以某种方式解决它,但是现在我想在内部调用onClick另一个内部的方法class(扩展SQLiteOpenhelper的DatabaseHelper)..

我做不到((DatabaseHelper)上下文).mymethod()所以我已经完成了以下“技巧”......在类MapsActivity中我以这种方式创建了一个方法(JoinPlayer):

public void JoinPlayer(Player player){
        databaseHelper.insertPlayer(player);
    }

DatabaseHelper中的insertPlayer(Player)是:

public void insertPlayer(Player player){
        try{
        db=this.getWritableDatabase();
        }
        catch(Exception e){
           Log.e("ERROR","ERROR");
        }
        ContentValues contentValues=new ContentValues();
        String query="select * from player";
        Cursor cursor=db.rawQuery(query,null);
        int count=cursor.getCount();

        contentValues.put(COLUMN_ID_PLAYER,count);
        contentValues.put(COLUMN_ID_MATCH_PLAYER,player.getId_partita());
        contentValues.put(COLUMN_ID_CONTACT_PLAYER,player.getId_contatto());

        db.insert(TABLE_PLAYER, null, contentValues);
        db.close();
    } 

但是Android建议我添加一个空条件(如果((MapsActivity)上下文)!= null)而不是((MapsActivity)上下文).JoinPlayer(播放器)但它告诉我它将永远为null,这正是我的意思得到......我认为背景是主要问题,但现在还没有线索如何解决它。有什么想法吗?

答案 3 :(得分:0)

好的......找到了解决方案......在MatchAdapter上扩展了ArrayAdapter

fetch("http://mydinners.fr:5280/partner") .then(res => res.json()) .then(json => { let binary = new Uint8Array(json.message[0].partner_image) let blob = new Blob([binary]) let img = new Image() img.src = URL.createObjectURL(blob) document.body.appendChild(img) }) ...比OnClick功能......

DatabaseHelper databaseHelper=new DatabaseHelper(getContext());