Mi pregunta es la siguiente:

Tengo una base de datos mysql en línea que he enlazado algunos datos a través de JSON a una vista de lista dentro de un fragmento. He hecho esto muchas veces antes con un adaptador de cursor de una base de datos sqlite local, pero ahora tengo algunos problemas con su JSON.

Los datos se muestran bien en la vista de lista personalizada, pero cuando hago clic en un elemento, me gustaría obtener la identificación (así como otras filas) de la base de datos en línea y pasarla a la siguiente actividad a través de intent.putExtra ().

Los datos se almacenan en un modelo, sin embargo, actualmente estoy configurando la visibilidad de ID TextView en "desaparecido" y simplemente almacenando el valor del texto de edición, sin embargo, esto no es muy eficiente ya que tengo muchas listas de vistas a través de la aplicación. No estoy seguro de si estoy iniciando el modelo correctamente, ya que me estaba dando errores, por lo que volví al método get.Text.toString para almacenar la ID.

¿Cómo obtengo la ID que está almacenada en el modelo desde el adaptador de matriz?

Saludos :) hay algo que simplemente no estoy entendiendo ...

ACTUALIZAR#

Después de agregar las líneas

DietNameModel dm = data.get(position);
        int id2 = dm.getDietID();

        String  weight_id = String.valueOf(id2);

        Toast.makeText(getActivity(), weight_id, Toast.LENGTH_LONG).show(); 

Obtengo el siguiente error en el logcat.

01-31 04:11:24.895: W/dalvikvm(1260): threadid=1: thread exiting with uncaught exception (group=0xa621c908)
01-31 04:11:24.899: E/AndroidRuntime(1260): FATAL EXCEPTION: main
01-31 04:11:24.899: E/AndroidRuntime(1260): java.lang.NullPointerException
01-31 04:11:24.899: E/AndroidRuntime(1260):     at com.dietmanager.main.DietsFragmentJSON$1.onItemClick(DietsFragmentJSON.java:100)
01-31 04:11:24.899: E/AndroidRuntime(1260):     at android.widget.AdapterView.performItemClick(AdapterView.java:298)
01-31 04:11:24.899: E/AndroidRuntime(1260):     at android.widget.AbsListView.performItemClick(AbsListView.java:1100)
01-31 04:11:24.899: E/AndroidRuntime(1260):     at android.widget.AbsListView$PerformClick.run(AbsListView.java:2749)
01-31 04:11:24.899: E/AndroidRuntime(1260):     at android.widget.AbsListView$1.run(AbsListView.java:3423)
01-31 04:11:24.899: E/AndroidRuntime(1260):     at android.os.Handler.handleCallback(Handler.java:725)
01-31 04:11:24.899: E/AndroidRuntime(1260):     at android.os.Handler.dispatchMessage(Handler.java:92)
01-31 04:11:24.899: E/AndroidRuntime(1260):     at android.os.Looper.loop(Looper.java:137)
01-31 04:11:24.899: E/AndroidRuntime(1260):     at android.app.ActivityThread.main(ActivityThread.java:5041)
01-31 04:11:24.899: E/AndroidRuntime(1260):     at java.lang.reflect.Method.invokeNative(Native Method)
01-31 04:11:24.899: E/AndroidRuntime(1260):     at java.lang.reflect.Method.invoke(Method.java:511)
01-31 04:11:24.899: E/AndroidRuntime(1260):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
01-31 04:11:24.899: E/AndroidRuntime(1260):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560)
01-31 04:11:24.899: E/AndroidRuntime(1260):     at dalvik.system.NativeStart.main(Native Method)

DietJSONFragmento

public class DietsFragmentJSON extends Fragment implements FetchDietNameListener  {

 private List<DietNameModel> data;
Activity mActivity;
View rootView;
private int dietID;
private ListView listview;
private String diet_ID, diet_name, diet_category, diet_desc ;
private ProgressDialog dialog;
private EditText et;
private ListView lv;
private TextView idTxt, weight_loss, diet_desc_text, diet_rating, diet_followers_txt, diet_duration;

private static List<DietNameModel> dietnamemodel;



public View onCreateView(LayoutInflater inflater, ViewGroup container,
        Bundle savedInstanceState) {



    rootView = inflater.inflate(R.layout.diet_name_fragment, container, false);

    listview = (ListView) rootView.findViewById(R.id.listview);

    mActivity = getActivity();

    initView();

    return rootView;


}


private void initView() {
    // show progress dialog
    dialog = ProgressDialog.show(mActivity, "", "Loading...");

    String url = "http:xxxxxxxxxxxxxxx.diet_name.php";
    FetchDietDataTask task = new FetchDietDataTask(this);
    task.execute(url);
}


public void onFetchComplete(List<DietNameModel> data) {
    // dismiss the progress dialog
    if(dialog != null)  dialog.dismiss();

    // create new adapter
    DietNameAdapter adapter = new DietNameAdapter(getActivity(), data);
    // set the adapter to list
    listview.setAdapter(adapter);      

    listview.setOnItemClickListener(myOnItemClickListener);
}

OnItemClickListener myOnItemClickListener
= new OnItemClickListener(){

    @SuppressLint("NewApi") @Override
    public void onItemClick(AdapterView<?> parent, View view, int position,
            long id) {

        //DietNameModel dm = data.get(position);
        //String dietname = dm.getDietName();

        //HERE NEED TO GET ID FROM THE MODEL 


idTxt = (TextView)view.findViewById(R.id.diet_iD);
dietID = Integer.valueOf(idTxt.getText().toString());


diet_name = ((TextView) view.findViewById(R.id.titleTxt)).getText().toString();


Intent intent = new Intent(getActivity(), DietActivity.class);

    Bundle bundle = ActivityOptions.makeCustomAnimation(getActivity(), R.anim.left_slide_in, R.anim.left_slide_out).toBundle();
    intent.putExtra("id", dietID);
intent.putExtra("dietname", diet_name);
    //intent.putExtra("diet_duration_string", diet_duration_String);
    getActivity().startActivity(intent, bundle);
  }
};

@Override
public void onFetchFailure(String msg) {
    // dismiss the progress dialog
    if(dialog != null)  dialog.dismiss();

    Toast.makeText(getActivity(), msg, Toast.LENGTH_LONG).show();
}
}

Modelo de nombre de dieta

public class DietNameModel {

private String diet_name;
private String diet_desc;
private long followers;
private int rating;
private int _id;
private int diet_duration;
private int weight_loss_total_kg;

private String diet_category;

public DietNameModel(){

}

public DietNameModel(int id, int diet_duration, int rating, long followers, String diet_name, String diet_desc, String diet_cat){

    this._id = id;
    this.rating = rating;
    this.followers = followers;
    this.diet_duration = diet_duration;
    this.diet_name = diet_name;
    this.diet_desc = diet_desc;
    this.diet_category = diet_cat;

}

public DietNameModel(String diet_name, String diet_desc, String diet_cat){

    this.diet_name = diet_name;
    this.diet_desc = diet_desc;
    this.diet_category = diet_cat;
}


public String getDietCategory() {
    return diet_category;
}
public void setDietCategory(String diet_category) {
    this.diet_category = diet_category;
}

public String getDietName() {
    return diet_name;
}
public void setDietName(String diet_name) {
    this.diet_name = diet_name;
}
public String getDietDesc() {
    return diet_desc;
}
public void setDietDesc(String diet_desc) {
    this.diet_desc = diet_desc;
}
public long getFollowers() {
    return followers;
}
public void setFollowers(long followers) {
    this.followers = followers;
}
public int getRating() {
    return rating;
}
public void setRating(int rating) {
    this.rating = rating;
}

public int getDietID() {
    return _id;
}
public void setDietID(int _id) {
    this._id = _id;
}

public int getTotalWeightLoss() {
    return weight_loss_total_kg;
}
public void setTotalWeightLoss(int weight_loss_total_kg) {
    this.weight_loss_total_kg = weight_loss_total_kg;
}
public int getDietDuration() {
    return diet_duration;
}
public void setDietDuration(int diet_duration) {
    this.diet_duration = diet_duration;
}
}

FetchDietDataTask

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

private final FetchDietNameListener listener;
private String msg;

public FetchDietDataTask(FetchDietNameListener listener) {
    this.listener = listener;
}

@Override
protected String doInBackground(String... params) {
    if(params == null) return null;

    // get url from params
    String url = params[0];

    try {
        // create http connection
        HttpClient client = new DefaultHttpClient();
        HttpGet httpget = new HttpGet(url);

        // connect
        HttpResponse response = client.execute(httpget);

        // get response
        HttpEntity entity = response.getEntity();

        if(entity == null) {
            msg = "No response from server";
            return null;        
        }

        // get response content and convert it to json string
        InputStream is = entity.getContent();
        return streamToString(is);
    }
    catch(IOException e){
        msg = "No Network Connection";
    }

    return null;
}

@Override
protected void onPostExecute(String sJson) {
    if(sJson == null) {
        if(listener != null) listener.onFetchFailure(msg);
        return;
    }        

    try {
        // convert json string to json array
        JSONArray aJson = new JSONArray(sJson);
        // create list list
        List<DietNameModel> dietnamemodellist = new ArrayList<DietNameModel>();

        for(int i=0; i<aJson.length(); i++) {
            JSONObject json = aJson.getJSONObject(i);
            DietNameModel dietnamemodel = new DietNameModel();

            dietnamemodel.setDietID(Integer.parseInt(json.getString("_id")));  
            dietnamemodel.setDietName(json.getString("diet_name"));
            dietnamemodel.setDietCategory(json.getString("diet_category"));
            dietnamemodel.setDietDuration(Integer.parseInt(json.getString("diet_duration")));  
            dietnamemodel.setTotalWeightLoss(Integer.parseInt(json.getString("total_weight_loss")));  
            dietnamemodel.setFollowers(Long.parseLong(json.getString("followers")));
            dietnamemodel.setRating(Integer.parseInt(json.getString("rating")));  
          // dietnamemodel.setIcon(json.getString("icon"));

            // add the name to list
            dietnamemodellist.add(dietnamemodel);
        }
        //notify the activity that fetch data has been complete
        if(listener != null) listener.onFetchComplete(dietnamemodellist);
    } catch (JSONException e) {
        msg = "Invalid response";
        if(listener != null) listener.onFetchFailure(msg);
        return;
    }        
}

/**
 * This function will convert response stream into json string
 * @param is respons string
 * @return json string
 * @throws IOException
 */
public String streamToString(final InputStream is) throws IOException{
    BufferedReader reader = new BufferedReader(new InputStreamReader(is));
    StringBuilder sb = new StringBuilder(); 
    String line = null;

    try {
        while ((line = reader.readLine()) != null) {
            sb.append(line + "\n");
        }
    } 
    catch (IOException e) {
        throw e;
    } 
    finally {           
        try {
            is.close();
        } 
        catch (IOException e) {
            throw e;
        }
    }

    return sb.toString();
}
}

DietNameAdapter

public class DietNameAdapter extends ArrayAdapter<DietNameModel>{

private List<DietNameModel> items;
private TextView diet_name, diet_cat, diet_duration, diet_weight_loss, diet_ID ;


private LinearLayout ratingCntr;
private TextView followersText;



public DietNameAdapter(Context context, List<DietNameModel> items) {
    super(context, R.layout.row_diet_name_dev);


    this.items = items;
}


public int getCount() {
    return items.size();
}


public View getView(int position, View convertView, ViewGroup parent) {
    View v = convertView;

    if(v == null) {
        LayoutInflater li = LayoutInflater.from(getContext());
        v = li.inflate(R.layout.row_diet_name_dev, null);            
    }

    DietNameModel infomodel = items.get(position);


    if(infomodel != null) {

        diet_ID = (TextView)v.findViewById(R.id.diet_iD);
         diet_name = (TextView)v.findViewById(R.id.titleTxt);
         ratingCntr = (LinearLayout)v.findViewById(R.id.ratingCntr);
         followersText  = (TextView)v.findViewById(R.id.followers);
         diet_cat = (TextView)v.findViewById(R.id.dietCatTxt);
         diet_duration = (TextView)v.findViewById(R.id.diet_duration_txt);
         diet_weight_loss =  (TextView)v.findViewById(R.id.diet_weight_lost);


         if( diet_ID != null) {
             NumberFormat nf2 = NumberFormat.getNumberInstance();
             diet_ID.setText(nf2.format(infomodel.getDietID()));            
         }


        if( diet_name != null)  diet_name.setText(infomodel.getDietName());

        if( diet_cat != null)  diet_cat.setText(infomodel.getDietCategory());



        if(followersText != null) {
            NumberFormat nf = NumberFormat.getNumberInstance();
            followersText.setText("Followers: " + nf.format(infomodel.getFollowers()));            
        }

        if( diet_duration != null) {
            NumberFormat nf2 = NumberFormat.getNumberInstance();
            diet_duration.setText(nf2.format(infomodel.getDietDuration()));            
        }

        if( diet_weight_loss != null) {
            NumberFormat nf2 = NumberFormat.getNumberInstance();
            diet_weight_loss.setText(nf2.format(infomodel.getTotalWeightLoss()));            
        }

        if(ratingCntr != null && ratingCntr.getChildCount() == 0) {        
            /*
             * max rating: 5
             */
            for(int i=1; i<=5; i++) {
                ImageView iv = new ImageView(getContext());

                if(i <= infomodel.getRating()) {
                    iv.setImageDrawable(getContext().getResources().getDrawable(R.drawable.start_checked));
                }


                ratingCntr.addView(iv);
            }
        }
    }

    return v;
}
}
1
user1673498 31 ene. 2015 a las 06:23

2 respuestas

La mejor respuesta

El puntero nulo se refería a la lista de datos que no se había configurado correctamente, el problema ahora se ha resuelto. la línea que debía agregarse era this.data = data;

public void onFetchComplete(List<DietNameModel> data) {
    this.data = data;

    if(dialog != null) 
        dialog.dismiss();

    // create new adapter
     adapter = new DietNameAdapter(getActivity(), data);
    // set the adapter to list
    listview.setAdapter(adapter);      

    listview.setOnItemClickListener(myOnItemClickListener);
}
1
Danielson 27 nov. 2015 a las 08:31

En el OnItemClickListener de su ListView, ¿intentó obtener el ID de esta manera?

OnItemClickListener myOnItemClickListener = new OnItemClickListener(){

    @SuppressLint("NewApi") @Override
    public void onItemClick(AdapterView<?> parent, View view, int position,
            long id) {

        DietNameModel dm = data.get(position);
        int id = dm.getDietID();
        ...
0
iRuth 31 ene. 2015 a las 04:03