How do I get the ID of a user in a ListView and use it as a variable in another Activity?

0

I'm doing my TCC and I'm having a hard time getting the ID of some ListView user and using it in another Activity (The intention is that when the user holds the click on someone else on the list, popup ) asking if he wants to send a friend request to that person (and for this I need to know the ID of the person chosen)

popAddAmigo.java

public class popAddAmigo extends Activity {

String urlAddress="http://192.168.1.107/line/Pesquisa.php";
// String urlAddress="http://172.16.2.15/line/Pesquisa.php";
SearchView sv;
ListView lv;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    setContentView(R.layout.popaddamigo);

    lv           = (ListView) findViewById(R.id.listaAmigos);
    sv           = (SearchView) findViewById(R.id.svPesquisa);

    sv.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
        @Override
        public boolean onQueryTextSubmit(String query) {
            SenderReceiver sr = new SenderReceiver(popAddAmigo.this, urlAddress, query, lv);
            sr.execute();
            return false;
        }

        @Override
        public boolean onQueryTextChange(String query) {
            SenderReceiver sr = new SenderReceiver(popAddAmigo.this, urlAddress, query, lv);
            sr.execute();
            return false;
        }
    });

    lv.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {

        @Override
        public boolean onItemLongClick(AdapterView<?> arg0, View arg1,
                                       final int pos, long id) {


            Intent abreAdd = new Intent(popAddAmigo.this, popAdd.class);
            startActivity(abreAdd);





            return false;
        }
    });

}

}

Parser.java

public class Parser extends AsyncTask<Void,Void,Integer> {

Context c;
String data;
ListView lv;

ArrayList<String> names = new ArrayList<>();

public Parser(Context c, String data, ListView lv) {

    this.c    = c;
    this.data = data;
    this.lv   = lv;

}

@Override
protected void onPreExecute() {
    super.onPreExecute();
}

@Override
protected Integer doInBackground(Void... params) {
    return this.parse();
}

@Override
protected void onPostExecute(Integer integer) {
    super.onPostExecute(integer);

    if(integer==1) {

        ArrayAdapter adapter = new ArrayAdapter(c,R.layout.listalayout,names);
        lv.setAdapter(adapter);

    } else {

        Toast.makeText(c,"Não encontramos resultado :(",Toast.LENGTH_SHORT).show();

    }
}

private int parse() {

    try {

        JSONArray ja = new JSONArray(data);
        JSONObject jo = null;
        names.clear();

        for(int i=0;i<ja.length();i++) {
            jo=ja.getJSONObject(i);
            String name = jo.getString("nome");
            names.add(name);

        }
        return 1;
    } catch (JSONException e) {
        e.printStackTrace();
    }
    return 0;
}
}

SenderReceiver.java

public class SenderReceiver extends AsyncTask<Void,Void,String> {

Context c;
String urlAddress;
String query;
ListView lv;
ProgressDialog pd;

public SenderReceiver(Context c, String urlAddress, String query, ListView lv,ImageView...imageViews) {

    this.c = c;
    this.urlAddress = urlAddress;
    this.query = query;
    this.lv = lv;

}

@Override
protected void onPreExecute() {

    super.onPreExecute();
    pd=new ProgressDialog(c);
    pd.setTitle("Pesquisando...");
    pd.setMessage("Por favor aguarde.");
    pd.show();

}

@Override
protected String doInBackground(Void... params) {
    return this.sendAndReceive();
}

@Override
protected void onPostExecute(String s) {
    super.onPostExecute(s);

    pd.dismiss();

    lv.setAdapter(null);

    if(s != null) {
        if(!s.contains("null")) {

            Parser p = new Parser(c,s,lv);
            p.execute();

        } else {

            Toast.makeText(c.getApplicationContext(), "Usuário não encontrado.", Toast.LENGTH_LONG).show();

        }
    } else {

        Toast.makeText(c.getApplicationContext(), "Nenhuma conexão com a Internet foi encontrada.", Toast.LENGTH_LONG).show();

    }
}

private String sendAndReceive()
{
    HttpURLConnection con = Connector.connect(urlAddress);

    if(con==null) {
        return null;
    } try {

        OutputStream os = con.getOutputStream();
        BufferedWriter bw=new BufferedWriter(new OutputStreamWriter(os));
        bw.write(new DataPackager(query).packageData());
        bw.flush();
        bw.close();
        os.close();
        int responseCode = con.getResponseCode();

        if(responseCode==con.HTTP_OK) {

            InputStream is = con.getInputStream();

            BufferedReader br = new BufferedReader(new InputStreamReader(is));
            String line;
            StringBuffer response = new StringBuffer();
            if(br != null) {
                while ((line=br.readLine()) != null) {
                    response.append(line+"n");
                }
            } else {
                return null;
            }
            return response.toString();
        } else {
            return String.valueOf(responseCode);
        }
    } catch (IOException e) {
        e.printStackTrace();
    }
    return null;
}
}

DataPackager.java

public class DataPackager {

String query;

public DataPackager(String query) {
    this.query = query;
}

public String packageData() {

    JSONObject jo = new JSONObject();
    StringBuffer queryString = new StringBuffer();

    try {

        jo.put("Query",query);
        Boolean firstValue = true;
        Iterator it = jo.keys();

        do {
            String key = it.next().toString();
            String value = jo.get(key).toString();
            if(firstValue) {
                firstValue = false;
            } else {
                queryString.append("&");
            }

            queryString.append(URLEncoder.encode(key,"UTF-8"));
            queryString.append("=");
            queryString.append(URLEncoder.encode(value,"UTF-8"));

        } while (it.hasNext());

        return queryString.toString();

    } catch (JSONException e) {
        e.printStackTrace();
    } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
    }
    return null;
}

}
    
asked by anonymous 01.09.2017 / 03:51

1 answer

2

Within the onItemLongClick(AdapterView<?> adapterView, ...) method you should get the user and pass it on within the attempt to start the activity.

@Override
public boolean onItemLongClick(AdapterView<?> adapterView, View arg1, final int pos, long id) {

    /*
    Converte do tipo Object para o tipo que você 
    passou no seu adapter, por exemplo:
    */
    Usuario usuario = (Usuario) adapterView.getItemAtPosition(pos);

    Intent abreAdd = new Intent(popAddAmigo.this, popAdd.class);
    // Aqui você passa o id para a intent, com a chave "idUsuario"
    abreAdd.putExtra("idUsuario", usuario.getId());
    startActivity(abreAdd);

    return true;
}

popAdd.java

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.pop_add);

    // Obtém o id do usuário
    int idUsuario = getIntent().getIntExtra("idUsuario", 0);
}

UPDATE

You will need a Usuario class to store your information. In your case, it would be the id and the name.

User.java

public class Usuario {
    private int id;
    private String nome;

    public Usuario(JSONObject object) {
        id = object.getInt("id");
        nome = object.getString("nome");
    }

    public int getId() {
        return id;
    }

    public String getNome() {
        return nome;
    }
}

You will also need a custom class to display the user in the list.

ExampleAdapter.java

public class ExampleAdapter extends ArrayAdapter<Usuario> {
    private final LayoutInflater inflater;

    private List<Usuario> usuarioList;

    public ExampleAdapter(@NonNull Context context, List<Usuario> usuarioList) {
        super(context, R.layout.listalayout);
        inflater = LayoutInflater.from(context);
        this.usuarioList = usuarioList;
    }

    @NonNull
    @Override
    public View getView(int position, @Nullable View convertView, @NonNull ViewGroup parent) {
        super.getView(position, convertView, parent);

        // Aqui você tem que verificar se o convertView está nulo,
        // porque pode acontecer de ele ser nulo
        if (convertView == null) {
            convertView = inflater.inflate(R.layout.listalayout, parent, false);
        }

        Usuario usuario = getItem(position);

        TextView txtNome = (TextView) convertView.findViewById(R.id.txt_nome);

        txtNome.setText(usuario.getNome());

        return convertView;
    }

    @Override
    public Usuario getItem(int position) {
        return usuarioList.get(position);
    }

    @Override
    public int getCount() {
        return usuarioList == null ? 0 : usuarioList.size();
    }
}

And lastly it changes its Parser to process a list of Usuarios instead of Strings .

Parser.java

public class Parser extends AsyncTask<Void,Void,Integer> {

    Context c;
    String data;
    ListView lv;

    ArrayList<Usuario> usuarios = new ArrayList<>();

    public Parser(Context c, String data, ListView lv) {

        this.c    = c;
        this.data = data;
        this.lv   = lv;

    }

    @Override
    protected void onPreExecute() {
        super.onPreExecute();
    }

    @Override
    protected Integer doInBackground(Void... params) {
        return this.parse();
    }

    @Override
    protected void onPostExecute(Integer integer) {
        super.onPostExecute(integer);

        if(integer==1) {

            ExampleAdapter adapter = new ExampleAdapter(c,usuarios);
            lv.setAdapter(adapter);

        } else {

            Toast.makeText(c,"Não encontramos resultado :(",Toast.LENGTH_SHORT).show();

        }
    }

    private int parse() {

        try {

            JSONArray ja = new JSONArray(data);
            usuarios.clear();

            for(int i=0;i<ja.length();i++) {
                usuarios.add(new Usuario(ja.getJSONObject(i)));

            }
            return 1;
        } catch (JSONException e) {
            e.printStackTrace();
        }
        return 0;
    }
}
    
01.09.2017 / 04:39