无法在listview中获取json数据

时间:2014-05-23 13:19:24

标签: android json listview android-listview

这是主要活动,我有 asynktask jsonparsor 文件..我想获取以下格式的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;
    }

}

}

2 个答案:

答案 0 :(得分:0)

更改此行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"));

答案 1 :(得分:0)

错误很少

更改此

 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

使用Custom 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());

使用列表

在textview中显示

编辑:

public class MyProfileActivity extends 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();
        }
    }
}

Returnjson.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);
    }
    }