【问题标题】:unable to fetch json data in listview [closed]无法在列表视图中获取 json 数据 [关闭]
【发布时间】:2014-05-23 13:19:24
【问题描述】:

这是主要活动,我有 asynktaskjsonparsor 文件.. 我想获取以下格式的 json dat:

{
    "status": 1,
    "records": [
        {
            "member_id": "10",
            "member_name": "RavinderKaur",
            "gender": "1",
            "dob": "15-7-2014",
            "email": "rv@gmail.com",
            "contact_no": "1234567891",
            "address": "",
            "member_password": "25d55ad283aa400af464c76d713c07ad",
            "member_designation": "",
            "created_date": "2014-05-18 22:49:34"
        }
    ]
}

代码:

public class MyProfileActivity extends Activity{

ListView mProfile ;

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

    mProfile = (ListView)findViewById(R.id.lvProfile);

}
    //getting link with json and asynktask

public void getdata(){
    JSONGetRequest jRequest = JSONGetRequest
            .getSingleInstance(MyProfileActivity.this);
    jRequest.execute(Tags.url);

    try {

        JSONObject result = jRequest.execute().get();

                    String status = result.getString("status");

                if (status.equals("1")){

                    ArrayList<MyProfile> arraylist = new ArrayList<MyProfile>();

                JSONArray array = result.getJSONArray("records");
        for(int i=0; i<=array.length(); i++){
            JSONObject json = array.getJSONObject(i);
            MyProfile objBeans = new MyProfile();
            objBeans.setName(json.getString("name"));
            arraylist.add(objBeans);

        }   
    }
}catch (InterruptedException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (ExecutionException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (JSONException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
            //doing try here for inserting data into adapter 
    ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
            android.R.layout.simple_list_item_1,arraylist);
        mProfile.setAdapter(adapter);
}

}

这是我的 JSONParsor 文件

package com.example.capo.net;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.StatusLine;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONException;
import org.json.JSONObject;

import android.util.Log;

public class JSONParser {

private static InputStream iStream = null;

private static String json = "";
private static JSONObject jObj = null;

public JSONParser() {
}

public JSONObject getJSONFromUrl(String url) {

    StringBuilder builder = new StringBuilder();

    HttpClient client = new DefaultHttpClient();

    HttpGet httpGet = new HttpGet(url);

    try {

        HttpResponse response = client.execute(httpGet);

        StatusLine statusLine = response.getStatusLine();

        int statusCode = statusLine.getStatusCode();

        if (statusCode == 200) {

            HttpEntity entity = response.getEntity();

            InputStream content = entity.getContent();

            BufferedReader reader = new BufferedReader(
                    new InputStreamReader(content));

            String line;

            while ((line = reader.readLine()) != null) {

                builder.append(line);
            }

        } else {
            Log.e("==>", "Failed to download file");
        }
    } catch (ClientProtocolException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }

    // Parse String to JSON object
    try {

        jObj = new JSONObject(builder.toString());
        // jarray = new JSONArray(builder.toString());
    } catch (JSONException e) {
        Log.e("JSON Parser", "Error parsing data " + e.toString());
    }

    // return JSON Object
    return jObj;

}
}

这是我的 AsynckTask 文件:

package com.example.capo.net;

import org.json.JSONObject;

import android.app.ProgressDialog;
import android.content.Context;
import android.os.AsyncTask;

public class JSONGetRequest extends AsyncTask<String, Void, JSONObject> {

private static Context mContext;
private static JSONGetRequest singleInstance;
private ProgressDialog mDialog;


public static JSONGetRequest getSingleInstance(Context context) {

    singleInstance = new JSONGetRequest();

    mContext = context;

    return singleInstance;
}

@Override
protected void onPreExecute() {
    // TODO Auto-generated method stub
    super.onPreExecute();

    mDialog = new ProgressDialog(mContext);
    mDialog.setMessage("Please wait");
    mDialog.show();

}

@Override
protected JSONObject doInBackground(String... params) {

    try {
        // Creating JSON Parser instance
        JSONParser jParser = new JSONParser();

        // getting JSON string from URL
        JSONObject json = jParser.getJSONFromUrl(params[0]);

        return json;

    } catch (Exception e) {

        System.out.println(e);
    }

    return null;

}

@Override
public void onPostExecute(JSONObject result) {
    // TODO Auto-generated method stub
    super.onPostExecute(result);

    mDialog.dismiss();
}
}

此文件用于 Beans:

package com.example.capo.beans;

public class MyProfile {

public String name , email,gender, dob, mobile,
 designation;

public String getName() {
    return name;
}

public void setName(String name) {
    this.name = name;
}

public String getEmail() {
    return email;
}

public void setEmail(String email) {
    this.email = email;
}

public String getGender() {
    return gender;
}

public void setGender(String gender) {
    this.gender = gender;
}

public String getDob() {
    return dob;
}

public void setDob(String dob) {
    this.dob = dob;
}

public String getMobile() {
    return mobile;
}

public void setMobile(String mobile) {
    this.mobile = mobile;
}

public String getDesignation() {
    return designation;
}

public void setDesignation(String designation) {
    this.designation = designation;
}
}

这是我能够正确存储数据的注册文件:

package com.example.capo.ui;

import java.util.concurrent.ExecutionException;

import org.json.JSONException;
import org.json.JSONObject;

import com.example.capo.R;
import com.example.capo.net.JSONGetRequest;
import com.example.capo.services.NotificationServices;
import com.example.capo.services.Tags;

import android.app.Activity;
import android.app.DatePickerDialog;
import android.app.DatePickerDialog.OnDateSetListener;
import android.content.Context;
import android.content.Intent;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.PopupWindow;
import android.widget.RadioButton;
import android.widget.Toast;

public class RformActivity extends Activity implements OnDateSetListener,
    OnClickListener {

// declaration of variables

private EditText mFirstName, mLastName, mEmail, mDob, mMobile,
        mPassword, mConfirmPassword, mdesignation;
private RadioButton mMale, mFemale;
private ImageView mSubmit;

public static String number, password;

private String gender;

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

    // reference from their Ids

    mFirstName = (EditText) findViewById(R.id.etFirstName);
    mLastName = (EditText) findViewById(R.id.etLastName);
    mEmail = (EditText) findViewById(R.id.etEmail);
    mDob = (EditText) findViewById(R.id.etDob);
    mMobile = (EditText) findViewById(R.id.etMobile);

    mPassword = (EditText) findViewById(R.id.etPassword);
    mConfirmPassword = (EditText) findViewById(R.id.etConfirmPassword);
    mdesignation = (EditText) findViewById(R.id.etDesignation);
    mMale = (RadioButton) findViewById(R.id.rbMale);
    mFemale = (RadioButton) findViewById(R.id.rbFemale);
    mSubmit = (ImageView) findViewById(R.id.btnSubmit);

    mDob.setOnClickListener(this);
    mSubmit.setOnClickListener(this);

    if(mMale.isChecked()){gender = "0";}else{ gender = "1"; }


}

// to show the date in given pattern
@Override
public void onDateSet(DatePicker arg0, int year, int month, int day) {

    String s = day + "-" + month + "-" + year;
    mDob.setText(s);

}

@Override
public void onClick(View arg0) {

    if (arg0 == mDob) {

        DatePickerDialog dt = new DatePickerDialog(RformActivity.this,
                (OnDateSetListener) RformActivity.this, 2014, 07, 15);
        dt.show();

    }

    if (arg0 == mSubmit) {

        String firstname = mFirstName.getText().toString();
        String lastname = mLastName.getText().toString();
        String email = mEmail.getText().toString();
        String dob = mDob.getText().toString();
        number = mMobile.getText().toString();
        password = mPassword.getText().toString();
        String confirmpassword = mConfirmPassword.getText().toString();
        String designation = mdesignation.getText().toString(); 

        if (firstname.equals("") || lastname.equals("") || email.equals("") || dob.equals("")
                || number.equals("") 
                || designation.equals("") || password.equals("")
                || confirmpassword.equals("")) {

            NotificationServices.showToast(getApplicationContext(),
                    "Fill the empty fields");

        }else if (isEmail(email)){

        if (number.length() < 10 || number.length() == 11) {

            NotificationServices.showToast(getApplicationContext(),
                    "Enter correct number");

        }else if (password.length() < 8) {

            NotificationServices.showToast(getApplicationContext(),
                    "Password should not be less than Eight");

        }else if (password.equals(confirmpassword)) {

            NotificationServices.showToast(getApplicationContext(),
                    "Checking for Sign Up");

            JSONGetRequest jRequest = JSONGetRequest
                    .getSingleInstance(RformActivity.this);

            try {

                String url = (Tags.url + "request=registration&name="
                        + (firstname+lastname) + "&gender=" + gender +"&email=" + email + "&mobile=" + number
                        + "&dob=" + dob + "&password=" + password + "&designation" + designation).replaceAll(" ", "%20");

                JSONObject result = jRequest.execute(url).get();

                if (result.getString("status").equals("1")) {

                    Intent intent = new Intent(RformActivity.this,
                            HomeTabActivity.class);

                    startActivity(intent);

                } else {

                    Toast.makeText(getApplicationContext(),
                                result.getString("message"), Toast.LENGTH_SHORT)
                            .show();

                }

            } catch (InterruptedException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (ExecutionException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (JSONException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }



        } else {

            NotificationServices.showToast(getApplicationContext(),
                    "Password not matches");

        }
    }
}
}

private boolean isEmail(String email) {

    if (email.contains("@")
            && email.contains(".")
            && email.indexOf("@") == email.lastIndexOf("@")
            && email.indexOf("@") != (email.indexOf(".") + 1)
            && (email.indexOf("@") + 1) != email.indexOf(".")
            && (!email.contains("^")) && (!email.contains(" "))
            && (!email.contains("-")) && (!email.contains("--"))) {

        return true;

    } else {

        NotificationServices.showToast(getApplicationContext(),
                "Enter correct Email.");
        return false;
    }

}

}

【问题讨论】:

    标签: android json listview android-listview


    【解决方案1】:

    错误很少

    改变这个

     ArrayList<MyProfile> arraylist = new ArrayList<MyProfile>();
    

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

    没有带有键name的json值

    arraylist.add(json.getString("member_name")); // its member_name
    

    将你的 for 循环更改为

    for(int i=0; i<array.length(); i++){ // you will get index out of bound excpetin
    // index starts from 0
    

    您的适配器将是

    ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
             android.R.layout.simple_list_item_1,arraylist);
    // this is just to display name
    

    使用自定义 ArrayAdapter 也是另一种方式

      if (status.equals("1")){
    
      ArrayList<MyProfile> arraylist = new ArrayList<MyProfile>();
    
      JSONArray array = result.getJSONArray("records");
      for(int i=0; i<array.length(); i++){
      JSONObject json = array.getJSONObject(i);
      MyProfile objBeans = new MyProfile();
      objBeans.setId(json.getString("member_id").toString());
      objBeans.setName(json.getString("member_name").toString());
      arraylist.add(mprofile);
     }
    

    然后

    CustomAdapter adapter = new CustomAdapter(this,arraylist);
    

    然后

    class CustomAdapter extends ArrayAdapter<MyProfile>
    {
        LayoutInflater mInflater;
        ArrayList<MyProfile> list;
        public CustomAdapter(Context context,ArrayList<MyProfile> list) {
            super(context, 0,list);
            mInflater = LayoutInflater.from(context);
            this.list=list;
        }
        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            // TODO Auto-generated method stub
            if(convertView==null)
            {
                convertView= mInflater.inflate(R.layout.customlayout,parent,false);
            }
            TextView tv = (TextView) convertView.findViewById(R.id.textView1);
            MyProfile mp = list.get(position);
            tv.setText(mp.getName());
            return convertView;
        }
    
    }
    

    自定义布局

    <?xml version="1.0" encoding="utf-8"?>
    <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:tools="http://schemas.android.com/tools"
        android:layout_width="match_parent"
        android:layout_height="match_parent" >
    
        <TextView
            android:id="@+id/textView1"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignParentTop="true"
            android:layout_centerHorizontal="true"
            android:layout_marginTop="20dp"
            android:text="TextView" />
    
    </RelativeLayout>
    

    使用 CustomAdapter,您还可以显示其他项目。只需在自定义布局中再添加一个文本视图

    MyProfile.java中有getter和setter

     objBeans.setName(json.getString("member_id").toString());
     objBeans.setName(json.getString("member_name").toString());
    

    使用列表在文本视图中显示

    编辑:

    公共类 MyProfileActivity 扩展 Activity 实现 Returnjson{

    ListView mProfile ;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        setContentView(R.layout.activity_my_profile);
        super.onCreate(savedInstanceState);
        mProfile = (ListView)findViewById(R.id.lvProfile);
         JSONGetRequest jRequest = JSONGetRequest
                    .getSingleInstance(MyProfileActivity.this);
            jRequest.execute("http://stagging.jandeccpl.com/testing/android_traning/carpool/ws/api.php?request=login&username=1234567891&password=12345678");
    
    }
    class CustomAdapter extends ArrayAdapter<MyProfile>
        {
            LayoutInflater mInflater;
            ArrayList<MyProfile> list;
            public CustomAdapter(Context context,ArrayList<MyProfile> list) {
                super(context, 0,list);
                mInflater = LayoutInflater.from(context);
                this.list=list;
            }
            @Override
            public View getView(int position, View convertView, ViewGroup parent) {
                // TODO Auto-generated method stub
                if(convertView==null)
                {
                    convertView= mInflater.inflate(R.layout.second,parent,false);
                }
                TextView tv = (TextView) convertView.findViewById(R.id.textView1);
                TextView tv1 = (TextView) convertView.findViewById(R.id.textView2);
                MyProfile mp = list.get(position);
                tv.setText(mp.getId());
                tv1.setText(mp.getName());
                return convertView;
            }
    
        }
        @Override
        public void returnjson(JSONObject result) {
            // TODO Auto-generated method stub
              try
                {
              //  JSONObject result = new JSONObject(load());
    
                String status = result.getString("status");
    
            if (status.equals("1")){
    
                ArrayList<MyProfile> arraylist = new ArrayList<MyProfile>();
    
             JSONArray array = result.getJSONArray("records");
             for(int i=0; i<array.length(); i++){
             JSONObject json = array.getJSONObject(i);
             MyProfile mprofile = new MyProfile();
             mprofile.setId(json.getString("member_id").toString());
             mprofile.setName(json.getString("member_name").toString());
             arraylist.add(mprofile);
             }  
             CustomAdapter adapter = new CustomAdapter(MyProfileActivity.this,arraylist);
             mProfile.setAdapter(adapter);
            }
                }catch(Exception e)
            {
                e.printStackTrace();
            }
        }
    }
    

    返回json.java

    public interface Returnjson {
      public void returnjson(JSONObject json);
    }
    

    JSONGetRequest.java

    public class JSONGetRequest extends AsyncTask<String, Void, JSONObject> {
    
        private static Context mContext;
        private static JSONGetRequest singleInstance;
        private ProgressDialog mDialog;
        Returnjson rt;
    
        public static JSONGetRequest getSingleInstance(Context context) {
    
            singleInstance = new JSONGetRequest();
    
            mContext = context;
    
            return singleInstance;
        }
    
        @Override
        protected void onPreExecute() {
            // TODO Auto-generated method stub
            super.onPreExecute();
            rt= (Returnjson) mContext;
            mDialog = new ProgressDialog(mContext);
            mDialog.setMessage("Please wait");
            mDialog.show();
    
        }
    
        @Override
        protected JSONObject doInBackground(String... params) {
    
            try {
                // Creating JSON Parser instance
                JSONParser jParser = new JSONParser();
    
                // getting JSON string from URL
                JSONObject json = jParser.getJSONFromUrl(params[0]);
    
                return json;
    
            } catch (Exception e) {
    
                System.out.println(e);
            }
    
            return null;
    
        }
    
        @Override
        public void onPostExecute(JSONObject result) {
            // TODO Auto-generated method stub
            super.onPostExecute(result);
    
            mDialog.dismiss();
            rt.returnjson(result);
        }
        }
    

    【讨论】:

    • 谢谢你我会用你的方式..但我希望你看到我上面发布的代码..我已经编辑了..我发布了所有的代码再次谢谢你
    • @user3663727 我看过你的帖子。 ArrayAdapter&lt;String&gt; 字符串类型的适配器。 ArrayList&lt;MyProfile&gt; MyProfile 的数组列表。你明白你正在做的错误吗??使用 arraylist 填充列表视图。
    • @user3663727 for 循环不正确。解析不正确。你最好使用自定义适配器,因为它有助于稍后显示 id 和其他项目
    • 好的,我用你的方式,如果有问题我会再发一次,感谢所有帮助我的朋友上帝保佑你们
    • arraylist.add(mprofile);现在问题来了,现在该怎么办
    【解决方案2】:

    更改此行json.getString("name")

    json.getString("member_name")
    

    因为你的 json 不包含 "name"

    编辑
    您在字符串适配器中插入 MyProfile 对象列表,这是错误的。 改变这个

    ArrayList<MyProfile> arraylist = new ArrayList<MyProfile>();
    

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

    还有这个

    MyProfile objBeans = new MyProfile();
                objBeans.setName(json.getString("name"));
                arraylist.add(objBeans);
    

    arraylist.add(json.getString("member_name"));
    

    【讨论】:

    • 但是你能告诉我我获取数据的方式是对的还是我做错了,因为运行时没有任何错误......但是数据没有被获取......
    • 你没有进入 JSONException 吗?
    • arraylist ArrayAdapter 显示错误适配器 = new ArrayAdapter(this, android.R.layout.simple_list_item_1,arraylist); mProfile.setAdapter(适配器);
    • 朋友实际上我有 JSONParsor 和 askytask 单独的文件..我能够通过 php 将数据存储在 mysql 中.. 但我无法获取我想在 listview 中显示的数据
    • 是的,Giru bai,我就像你说的那样使用了,但仍然没有发生任何事情
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-09-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-12-05
    • 1970-01-01
    相关资源
    最近更新 更多