How to take a user’s ID in a Listview and use as a variable in another Activity?

Asked

Viewed 304 times

0

I’m doing my TCC and I’m having trouble removing the ID of some user from Listview and using it in another Activity (The intention is that when the user holds the click on someone from the list, a popup (popAdd) appears asking if he wants to send a friend request to that person (And for that I need to know the ID of the chosen person)

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;
}

}
  • Your class Parser is with the content of SenderReceiver. You can update it?

  • All right, I’ve updated

  • Within the method parse() of your Parser, you have a Jsonobject jo. Inside it you have the user id too or just the name? Equal in jo.getString("nome"), only you would jo.getString("id")

  • Only the name, so if I do with the id will work? I tried here and nothing..

  • No. Only the id will not work either, but you need both. I will update the answer...

1 answer

2


Within the method onItemLongClick(AdapterView<?> adapterView, ...) you must get the user and pass it inside the Intent 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;
}

java popAdd.

@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);
}

UPDATING

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

Java user.

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 finally changes your 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;
    }
}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.