简体   繁体   English

Android-在Activity类和Adapter类之间传递数据

[英]Android - pass data between from an Activity class to an Adapter class

I have 3 classes: LoginActivity,MapsActivity and MatchAdapter 我有3个类别:LoginActivity,MapsActivity和MatchAdapter

The first 2 extends AppCompactActivity, the last one ArrayAdapter. 前两个扩展了AppCompactActivity,后一个扩展了ArrayAdapter。 When i make login (if correct, matching on mySQLiteDB) i used to get ID_contact of current user and pass it to MapsActivity with intent in such way: 当我进行登录时(如果正确,则在mySQLiteDB上匹配),我曾经使用以下方式获取当前用户的ID_contact并将其传递给MapsActivity:

On my LoginActivity: 在我的LoginActivity上:

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

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

On MapsActivity i can easily retrieve this data in such way: 在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();
}

Till now everything works fine, it appears the id of the current user. 到现在为止一切正常,它显示了当前用户的ID。 My problem is to pass this data (with intent i don't know how) even to another class named MatchAdapter that extends ArrayAdapter. 我的问题是甚至将此数据(故意不知道如何)传递给另一个名为MatchAdapter的类,该类扩展了ArrayAdapter。

I tried this way on MapsActivity: 我在MapsActivity上尝试过这种方式:

public class MapsActivity extends AppCompatActivity implements ...{

public  String getId_contact(){

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


        return contact;
    }

So on MatchAdaper trying to retrieve such way: 因此,在MatchAdaper上尝试检索这种方式:

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

But nothing..i get NULLPOINTEREXCEPTION...Can someone help me? 但是什么都没有。我得到NULLPOINTEREXCEPTION ...有人可以帮助我吗?

那么,您可以通过以下方式从适配器访问活动方法,即从适配器的构造函数或所需的任何位置调用此方法。

((ActivityName)context).methodName();

When you create a new instance of MapsActivity, that isn't the same Activity instance you got when you called startActivity(). 创建MapsActivity的新实例时,这与调用startActivity()时获得的Activity实例不同。 This is basically why you have a null pointer exception. 这基本上就是为什么您有一个空指针异常的原因。

More importantly, you should never be manually creating Activity instances using "new". 更重要的是,您绝不应该使用“新”手动创建活动实例。 Generally the system creates Activity objects for you via mechanisms like startActivity(), and that is how you should obtain them. 通常,系统通过诸如startActivity()之类的机制为您创建Activity对象,这就是您应该如何获取它们的方式。

Himanshu's suggestion can work, if your activity does happen to be "hosting" your adapter, but this isn't always guaranteed. 如果您的活动确实是在“托管”适配器,那么Himanshu的建议可以奏效,但这并不总是可以保证的。 A better approach is to pass the ID to your MatchAdapter directly, either in the constructor or as a direct setter function. 更好的方法是将ID直接传递给您的MatchAdapter,无论是在构造函数中还是作为直接设置函数。 At the least, you should perform a "instanceof" check to make sure your adapter context is really of type MapsActivity. 至少,您应该执行“ instanceof”检查,以确保您的适配器上下文确实是MapsActivity类型。

That's my MatchAdapter `package vincenzo.futsal4you; 那就是我的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;

        }


    }
}

` So the problem was that i declared a String (id_contatto3) inside a static (inner) class (MatchHolder).Declaring it up to MatchAdapter i solve it somehow, but now i wanna call inside onClick a method that is inside another class (DatabaseHelper that extends SQLiteOpenhelper).. `所以问题是我在一个静态(内部)类(MatchHolder)中声明了一个String(id_contatto3)。通过MatchAdapter声明它,我以某种方式解决了这个问题,但是现在我想在onClick内部调用另一个类(DatabaseHelper)中的方法扩展了SQLiteOpenhelper)。

I can't do ((DatabaseHelper)context).mymethod() So i've done the following "trick"...inside class MapsActivity where i've created a method (JoinPlayer) in such way: 我无法执行((DatabaseHelper)context).mymethod()所以我在MapsActivity类中完成了以下“技巧”,在其中我以这种方式创建了方法(JoinPlayer):

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

where insertPlayer(Player) in DatabaseHelper is: 其中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();
    } 

But Android suggest me to add a null condition(if ((MapsActivity)context)!=null) than ((MapsActivity)context).JoinPlayer(player) but it advise me it will be Always null and that's exactly what I get... I think is the context the main problem but have no clue right now how to solve it. 但是Android建议我添加一个空条件(如果(((MapsActivity)context)!= null)比((MapsActivity)context).JoinPlayer(player),但它告诉我它将始终为null,这正是我所得到的。我认为上下文是主要问题,但是现在不知道如何解决。 Any Idea? 任何想法?

Ok...found the solution...On MatchAdapter extends ArrayAdapter 好...找到解决方案...在MatchAdapter上扩展ArrayAdapter

DatabaseHelper databaseHelper=new DatabaseHelper(getContext()); ...than OnClick function.... ...比OnClick功能...

databaseHelper.myfunction();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM