从mysql JSON获取数据到Listview从模型获取ID

时间:2015-01-31 03:23:54

标签: php android mysql json listview

我的问题如下:

我有一个在线mysql数据库,我通过JSON将一些数据绑定到片段内的列表视图。我之前使用本地sqlite数据库中的游标适配器已经多次这样做了,但我现在遇到了一些JSON问题。

数据显示在自定义列表视图中,但是当我点击一个项目时,我想从在线数据库中获取ID(以及其他行)并通过intent.putExtra()将其传递给下一个活动

数据存储在一个模型中,但是目前我正在将ID TextView的可见性设置为“已消失”,只是存储编辑文本的值,但这并不是非常有效,因为我在应用程序中有很多列表视图。我不确定我是否正确启动模型,因为它给了我错误,因此我又回到了用于存储ID的get.Text.toString方法。

如何从阵列适配器获取存储在模型中的ID?

干杯:)有些东西我没得到......

UPDATE#

添加行后

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

        String  weight_id = String.valueOf(id2);

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

我在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)

DietJSONFragment

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

饮食名称模型

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

2 个答案:

答案 0 :(得分:1)

空指针指向未正确设置的数据列表,问题现已解决。必须添加的行是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 :(得分:0)

在ListView的OnItemClickListener中,您是否尝试获取此ID:

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();
        ...