1. java
  2. android
  3. c#
  4. .net
  5. javascript
  6. php
  7. jquery
  8. html
  9. sql

Retrofit - Buscando dados no BD cadastrados pelo ID do user...

Olá... Estou realizando um projeto, em que um usuário logado (que recebeu um ID) possa ver e editar apenas os itens que ele cadastrou no banco de dados. Sempre que ele salva um item, seu ID e salvo junto. Encontrei um projeto que possui o que preciso, mas falta editá-lo, para que retorne apenas os itens cadastrados pelo usuário. Minha dúvida é a seguinte: Como fazer para que ele visualize apenas esses dados? Agradeço a todos que possam ajudar...

Seguem os códigos:

AppConfig

public class AppConfig {

    public interface insert {
        @FormUrlEncoded
        @POST("retrofitcrud/insertData.php")
        void insertData(
                @Field("name") String name,
                @Field("age") String age,
                @Field("mobile") String mobile,
                @Field("email") String email,
                Callback<Response> callback);
    }

    public interface read {
        @GET("retrofitcrud/displayAll.php")
        void readData(Callback<JsonElement> callback);
    }

    public interface delete {
        @FormUrlEncoded
        @POST("retrofitcrud/deleteData.php")
        void deleteData(
                @Field("id") String id,
                Callback<Response> callback);
    }

    public interface update {
        @FormUrlEncoded
        @POST("retrofitcrud/updateData.php")
        void updateData(
                @Field("id") String id,
                @Field("name") String name,
                @Field("age") String age,
                @Field("mobile") String mobile,
                @Field("email") String email,
                Callback<Response> callback);
    }

}

ListViewAdapter

public class ListViewAdapter extends BaseAdapter {

    private final Context context;
    private final ArrayList<String> id;
    private final ArrayList<String> name;
    private final ArrayList<String> age;
    private final ArrayList<String> mobile;
    private final ArrayList<String> email;
    LayoutInflater layoutInflater;

    public ListViewAdapter(Context ctx, ArrayList<String> id, ArrayList<String> name, ArrayList<String> age,
                           ArrayList<String> mobile, ArrayList<String> email) {
        this.context = ctx;
        this.id = id;
        this.name = name;
        this.age = age;
        this.mobile = mobile;
        this.email = email;

    }

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

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

    @Override
    public long getItemId(int position) {
        return position;
    }

    @SuppressLint("ViewHolder")
    @Override
    public View getView(final int position, View view, ViewGroup parent) {

        Holder holder = new Holder();
        layoutInflater = (LayoutInflater) context.getSystemService
                (Context.LAYOUT_INFLATER_SERVICE);

        view = layoutInflater.inflate(R.layout.list_retrofit_item, null);
        holder.txt_name=(TextView)view.findViewById(R.id.name);
        holder.txt_age=(TextView)view.findViewById(R.id.age);
        holder.txt_mobile=(TextView)view.findViewById(R.id.mobile);
        holder.txt_mail=(TextView)view.findViewById(R.id.mail);

        holder.txt_name.setText(name.get(position));
        holder.txt_age.setText(age.get(position));
        holder.txt_mobile.setText(mobile.get(position));
        holder.txt_mail.setText(email.get(position));

        return view;
    }

    static class Holder {
        TextView txt_name,txt_age,txt_mobile,txt_mail;
    }
}

MainActivity

public class MainActivity extends AppCompatActivity {

    String BASE_URL = "http://www.delaroystudios.com";

    EditText edt_name, edt_age, edt_mobile, edt_mail;
    Button btn_insert, btn_display;

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

        edt_name = (EditText) findViewById(R.id.name);
        edt_age = (EditText) findViewById(R.id.age);
        edt_mobile = (EditText) findViewById(R.id.mobile);
        edt_mail = (EditText) findViewById(R.id.mail);
        btn_insert = (Button) findViewById(R.id.insert);
        btn_display = (Button) findViewById(R.id.retrieve);

        btn_insert.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                insert_data();
            }
        });

        btn_display.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent i = new Intent(getApplicationContext(), DisplayData.class);
                startActivity(i);
            }
        });
    }

    public void insert_data() {

        RestAdapter adapter = new RestAdapter.Builder()
                .setEndpoint(BASE_URL) //Setting the Root URL
                .build();

        AppConfig.insert api = adapter.create(AppConfig.insert.class);

        api.insertData(
                edt_name.getText().toString(),
                edt_age.getText().toString(),
                edt_mobile.getText().toString(),
                edt_mail.getText().toString(),
                new Callback<Response>() {
                    @Override
                    public void success(Response result, Response response) {

                        try {

                            BufferedReader reader = new BufferedReader(new InputStreamReader(result.getBody().in()));
                            String resp;
                            resp = reader.readLine();
                            Log.d("success", "" + resp);

                            JSONObject jObj = new JSONObject(resp);
                            int success = jObj.getInt("success");

                            if(success == 1){
                                Toast.makeText(getApplicationContext(), "Successfully inserted", Toast.LENGTH_SHORT).show();
                            } else{
                                Toast.makeText(getApplicationContext(), "Insertion Failed", Toast.LENGTH_SHORT).show();
                            }

                        } catch (IOException e) {
                            Log.d("Exception", e.toString());
                        } catch (JSONException e) {
                            Log.d("JsonException", e.toString());
                        }
                    }

                    @Override
                    public void failure(RetrofitError error) {
                        Toast.makeText(MainActivity.this, error.toString(), Toast.LENGTH_LONG).show();
                    }
                }
        );
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }

}

DisplayData

public class DisplayData extends AppCompatActivity {

    String BASE_URL = "http://www.delaroystudios.com";

    ListView details_list;
    ListViewAdapter displayAdapter;
    ArrayList<String> id = new ArrayList<>();
    ArrayList<String> name = new ArrayList<>();
    ArrayList<String> age = new ArrayList<>();
    ArrayList<String> mobile = new ArrayList<>();
    ArrayList<String> email = new ArrayList<>();

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

        details_list = (ListView) findViewById(R.id.retrieve);
        displayAdapter = new ListViewAdapter(getApplicationContext(), id, name, age, mobile, email);
        displayData();

        details_list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long ids) {
                Intent i = new Intent(getApplicationContext(),UpdateData.class);
                i.putExtra("id",id.get(position));
                i.putExtra("name",name.get(position));
                i.putExtra("age",age.get(position));
                i.putExtra("mobile",mobile.get(position));
                i.putExtra("email", email.get(position));
                startActivity(i);

            }
        });

        details_list.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
            @Override
            public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long ids) {
                delete(id.get(position));
                return true;
            }
        });
    }


    public void displayData() {

        RestAdapter adapter = new RestAdapter.Builder()
                .setEndpoint(BASE_URL) //Setting the Root URL
                .build();

        AppConfig.read api = adapter.create(AppConfig.read.class);

        api.readData(new Callback<JsonElement>() {
                         @Override
                         public void success(JsonElement result, Response response) {

                             String myResponse = result.toString();
                             Log.d("response", "" + myResponse);

                             try {
                                 JSONObject jObj = new JSONObject(myResponse);

                                 int success = jObj.getInt("success");

                                 if (success == 1) {

                                     JSONArray jsonArray = jObj.getJSONArray("details");
                                     for (int i = 0; i < jsonArray.length(); i++) {

                                         JSONObject jo = jsonArray.getJSONObject(i);

                                         id.add(jo.getString("id"));
                                         name.add(jo.getString("name"));
                                         age.add(jo.getString("age"));
                                         mobile.add(jo.getString("mobile"));
                                         email.add(jo.getString("email"));

                                     }

                                     details_list.setAdapter(displayAdapter);

                                 } else {
                                     Toast.makeText(getApplicationContext(), "No Details Found", Toast.LENGTH_SHORT).show();
                                 }
                             } catch (JSONException e) {
                                 Log.d("exception", e.toString());
                             }
                         }

                         @Override
                         public void failure(RetrofitError error) {
                             Log.d("Failure", error.toString());
                             Toast.makeText(DisplayData.this, error.toString(), Toast.LENGTH_LONG).show();
                         }
                     }
        );
    }

    public void delete(String id){

        RestAdapter adapter = new RestAdapter.Builder()
                .setEndpoint(BASE_URL) //Setting the Root URL
                .build();

        AppConfig.delete api = adapter.create(AppConfig.delete.class);

        api.deleteData(
                id,
                new Callback<Response>() {
                    @Override
                    public void success(Response result, Response response) {

                        try {

                            BufferedReader reader = new BufferedReader(new InputStreamReader(result.getBody().in()));
                            String resp;
                            resp = reader.readLine();
                            Log.d("success", "" + resp);

                            JSONObject jObj = new JSONObject(resp);
                            int success = jObj.getInt("success");

                            if(success == 1){
                                Toast.makeText(getApplicationContext(), "Successfully deleted", Toast.LENGTH_SHORT).show();
                                recreate();
                            } else{
                                Toast.makeText(getApplicationContext(), "Deletion Failed", Toast.LENGTH_SHORT).show();
                            }

                        } catch (IOException e) {
                            Log.d("Exception", e.toString());
                        } catch (JSONException e) {
                            Log.d("JsonException", e.toString());
                        }
                    }

                    @Override
                    public void failure(RetrofitError error) {
                        Toast.makeText(DisplayData.this, error.toString(), Toast.LENGTH_LONG).show();
                    }
                }
        );

    }

}

UpdateData

public class UpdateData extends AppCompatActivity {

    String BASE_URL = "http://www.delaroystudios.com";

    EditText edt_name, edt_age, edt_mobile, edt_mail;
    Button btn_update;

    String id, name, age, mobile, email;

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

        edt_name = (EditText) findViewById(R.id.name);
        edt_age = (EditText) findViewById(R.id.age);
        edt_mobile = (EditText) findViewById(R.id.mobile);
        edt_mail = (EditText) findViewById(R.id.mail);
        btn_update = (Button) findViewById(R.id.update);

        Intent i = getIntent();
        id = i.getStringExtra("id");
        name = i.getStringExtra("name");
        age = i.getStringExtra("age");
        mobile = i.getStringExtra("mobile");
        email = i.getStringExtra("email");

        edt_name.setText(name);
        edt_age.setText(age);
        edt_mobile.setText(mobile);
        edt_mail.setText(email);

        btn_update.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                update_data(id);

            }
        });

    }

    public void update_data(String id) {

        RestAdapter adapter = new RestAdapter.Builder()
                .setEndpoint(BASE_URL) //Setting the Root URL
                .build();

        AppConfig.update api = adapter.create(AppConfig.update.class);

        api.updateData(
                id,
                edt_name.getText().toString(),
                edt_age.getText().toString(),
                edt_mobile.getText().toString(),
                edt_mail.getText().toString(),
                new Callback<Response>() {
                    @Override
                    public void success(Response result, Response response) {

                        try {

                            BufferedReader reader = new BufferedReader(new InputStreamReader(result.getBody().in()));
                            String resp;
                            resp = reader.readLine();
                            Log.d("success", "" + resp);

                            JSONObject jObj = new JSONObject(resp);
                            int success = jObj.getInt("success");

                            if (success == 1) {
                                Toast.makeText(getApplicationContext(), "Successfully updated", Toast.LENGTH_SHORT).show();
                                startActivity(new Intent(getApplicationContext(),DisplayData.class));
                                finish();
                            } else {
                                Toast.makeText(getApplicationContext(), "Update Failed", Toast.LENGTH_SHORT).show();
                            }

                        } catch (IOException e) {
                            Log.d("Exception", e.toString());
                        } catch (JSONException e) {
                            Log.d("JsonException", e.toString());
                        }
                    }

                    @Override
                    public void failure(RetrofitError error) {
                        Toast.makeText(UpdateData.this, error.toString(), Toast.LENGTH_LONG).show();
                    }
                }
        );
    }

}
  1. Você vai ver essas setas em qualquer página de pergunta. Com elas, você pode dizer se uma pergunta ou uma resposta foram relevantes ou não.
  2. Edite sua pergunta ou resposta caso queira alterar ou adicionar detalhes.
  3. Caso haja alguma dúvida sobre a pergunta, adicione um comentário. O espaço de respostas deve ser utilizado apenas para responder a pergunta.
  4. Se o autor da pergunta marcar uma resposta como solucionada, esta marca aparecerá.
  5. Clique aqui para mais detalhes sobre o funcionamento do GUJ!

0 resposta

Não é a resposta que estava procurando? Procure outras perguntas com as tags rest ou faça a sua própria pergunta.