my json get only single value from json file - android

below is my json code but it return only single value from json file i am getting only single Friday from json file but actually in json file there is 4 Fridays how do i get all values of Friday ?
when i run my code ListView only show this Friday value "dish_name":"Hamburger", how i get all four values of Friday
{
"status": 1,
"data": [{
"school_name": "LittleStar ",
"calendar_id": "1",
"menu_title": "Atypical Menu",
"dish_name": "Mandarin Chicken Rice Bowl",
"dish_id": "210",
"day": "Fri",
"Schedule": "weekly"
}, {
"school_name": "LittleStar ",
"calendar_id": "1",
"menu_title": "Atypical Menu",
"dish_name": "Chicken Burger",
"dish_id": "206",
"day": "Fri",
"Schedule": "weekly"
}, {
"school_name": "LittleStar ",
"calendar_id": "1",
"menu_title": "Atypical Menu",
"dish_name": "Garden Fresh Salad",
"dish_id": "211",
"day": "Fri",
"Schedule": "weekly"
},
{
"school_name": "LittleStar ",
"calendar_id": "1",
"menu_title": "Atypical Menu",
"dish_name": "A Test",
"dish_id": "213",
"day": "Mon",
"Schedule": "weekly"
}, {
"school_name": "LittleStar ",
"calendar_id": "1",
"menu_title": "Atypical Menu",
"dish_name": "Hamburger",
"dish_id": "56",
"day": "Fri",
"Schedule": "weekly"
}, {
"school_name": "LittleStar ",
"calendar_id": "1",
"menu_title": "Atypical Menu",
"dish_name": "Tofu Caesar Salad w\/ Roll",
"dish_id": "149",
"day": "Fri",
"Schedule": "weekly"
}]
}
HelloworldActivity.java
public class HelloworldActivity extends Activity {
int count = 0;
Date date1;
Date date2;
String id;
String title;
String byweekdate;
int IOConnect = 0;
String mVal2;
String mVal3;
String mVal9;
String SelectMenuAPI;
String url;
String URL;
String URL2, URL3, URL4;
String menu_title;
JSONArray school;
ListView listCategory;
String status;
String message;
String _response;
String SelectMenuAPI2;
TextView menu_nametxt;
thirdstepAdapter cla;
static ArrayList<Long> Category_ID = new ArrayList<Long>();
static ArrayList<String> school_name = new ArrayList<String>();
static ArrayList<String> menu_name = new ArrayList<String>();
static ArrayList<String> dish_name = new ArrayList<String>();
static ArrayList<String> dish_ID = new ArrayList<String>();
static ArrayList<String> day = new ArrayList<String>();
static ArrayList<Long> Vacation_ID = new ArrayList<Long>();
static ArrayList<String> Vacation_name = new ArrayList<String>();
static ArrayList<String> Vacation_Date = new ArrayList<String>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
listCategory = (ListView) findViewById(R.id.thirdscreenlist);
menu_nametxt = (TextView) findViewById(R.id.menu_name);
cla = new thirdstepAdapter(HelloworldActivity.this);
listCategory.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> arg0, View arg1,
int position, long arg3) {
}
});
new getDataTask().execute();
}
void clearData() {
Category_ID.clear();
school_name.clear();
menu_name.clear();
dish_name.clear();
dish_ID.clear();
day.clear();
Vacation_ID.clear();
Vacation_name.clear();
Vacation_Date.clear();
}
public class getDataTask extends AsyncTask<Void, Void, Void> {
getDataTask() {
}
#Override
protected void onPreExecute() {
// TODO Auto-generated method stub
}
#Override
protected Void doInBackground(Void... arg0) {
// TODO Auto-generated method stub
parseJSONData();
return null;
}
#Override
protected void onPostExecute(Void result) {
// TODO Auto-generated method stub
if ((Category_ID.size() > 0) || IOConnect == 0) {
listCategory.setAdapter(cla);
menu_nametxt.setText(mVal2);
// cla.notifyDataSetChanged();
}
}
}
public void parseJSONData() {
clearData();
SelectMenuAPI = "http://198.57.208.46/~school/index.php/api/index/getMenuBySchool?sid=147&lid=1";
URL = SelectMenuAPI;
URL2 = URL.replace(" ", "%20");
try {
Log.i("url", "" + URL2);
HttpClient client = new DefaultHttpClient();
HttpConnectionParams
.setConnectionTimeout(client.getParams(), 15000);
HttpConnectionParams.setSoTimeout(client.getParams(), 15000);
HttpUriRequest request = new HttpGet(URL2);
HttpResponse response = client.execute(request);
HttpEntity resEntity = response.getEntity();
_response = EntityUtils.toString(resEntity);
JSONObject json2 = new JSONObject(_response);
status = json2.getString("status");
if (status.equals("1")) {
JSONArray school = json2.getJSONArray("data");
for (int i = 0; i < school.length(); i++) {
JSONObject object = school.getJSONObject(i);
if (count == 1) {
count = 0;
break;
} else
if (object.getString("Schedule").equals("weekly")) {
if (object.getString("day").equals("Fri")) {
Category_ID.add((long) i);
school_name.add(object.getString("school_name"));
dish_ID.add(object.getString("dish_id"));
dish_name.add(object.getString("dish_name"));
menu_name.add(object.getString("menu_title"));
day.add(object.getString("day"));
count = count + 1;
String[] mVal = new String[school.length()];
for (int k = 0; k < school.length(); k++) {
mVal[k] = school.getJSONObject(k).getString(
"menu_title");
message = "weekly";
mVal2 = mVal[0];
// count = count + 1;
}
} else {
}
} else if (object.getString("Schedule").equals("biweekly")) {
if (object.getString("day").equals(byweekdate)) {
Category_ID.add((long) i);
school_name.add(object.getString("school_name"));
menu_name.add(object.getString("menu_title"));
day.add(object.getString("day"));
String[] mVal = new String[school.length()];
for (int k = 0; k < school.length(); k++) {
mVal[k] = school.getJSONObject(k).getString(
"menu_title");
}
message = "weekly";
mVal2 = mVal[0];
dish_name.add(object.getString("dish_name"));
count = count + 1;
} else {
}
} else {
}
}
} else {
}
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
IOConnect = 1;
e.printStackTrace();
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}

Try like this hope this help u
try {
JSONObject jb = new JSONObject(myjsonstring);
String totalitems = jb.getString("totalItems");
Log.i("......", "" + totalitems);
String totalpages = jb.getString("totalPages");
String itemsPerPage = jb.getString("itemsPerPage");
String currentPage = jb.getString("currentPage");
JSONArray jarr = jb.getJSONArray("items");
for (int i = 0; i < jarr.length(); i++) {
JSONObject jb1 = jarr.getJSONObject(i);
String id = jb1.getString("id");
String categoy = jb1.getString("category");
String title = jb1.getString("title");
String pic = jb1.getString("thumbnail");
Log.i("........", id);
}
} catch (Exception e) {
}
//HTTP CLASS
public static String sendRequest(String url) {
String result = "";
try {
HttpClient client = new DefaultHttpClient();
HttpParams httpParameters = client.getParams();
HttpConnectionParams.setConnectionTimeout(httpParameters, 5000);
HttpConnectionParams.setSoTimeout(httpParameters, 5000);
HttpConnectionParams.setTcpNoDelay(httpParameters, true);
HttpGet request = new HttpGet();
request.setURI(new URI(url));
HttpResponse response = client.execute(request);
InputStream ips = response.getEntity().getContent();
BufferedReader buf = new BufferedReader(new InputStreamReader(ips,"UTF-8"));
StringBuilder sb = new StringBuilder();
String s;
while (true) {
s = buf.readLine();
if (s == null || s.length() == 0)
break;
sb.append(s);
}
buf.close();
ips.close();
result = sb.toString();
} catch (Exception e) {
e.printStackTrace();
}
return result;
}

Related

How to parse Json Array and Json Object having two keys and values in android?

I want to populate my spinner from wallet array from SQL database and then store the wallet id which is being selected by the user in the particular user details, not the wallet name. I have written this particular code and o have added the screenshot as well for the error.
Android Part
public class User extends AppCompatActivity {
ArrayAdapter<String> adapter;
ArrayList<Populate> listItems;
LinkedHashMap<String,String> walletId;
Button logout,editdetails;
SharedPreferences sp;
SharedPreferences.Editor editor;
public static final String DEFAULT = "N/A";
TextView usermail;
String email;
int id;
public static final int DEFAULTI = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_user);
listItems = new ArrayList<>();
usermail = (TextView) findViewById(R.id.usermail);
editdetails = (Button) findViewById(R.id.editdetails);
logout = (Button) findViewById(R.id.logout);
sp = getSharedPreferences("Login", Context.MODE_PRIVATE);
email = sp.getString("email", DEFAULT);
usermail.setText("Welcome " + email);
id = sp.getInt("id",DEFAULTI);
logout.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
/** pref = getSharedPreferences("Login", Context.MODE_PRIVATE);
editor = pref.edit();
editor.putBoolean("loginfirst",false);
editor.commit();**/
Intent i = new Intent(User.this, Login.class);
startActivity(i);
finish();
}
});
}
public void onEdit(View v){
BackgroundTask backgroundTask = new BackgroundTask();
backgroundTask.execute(String.valueOf(id));
}
class BackgroundTask extends AsyncTask<String, Void, String> {
ArrayList<Populate> list;
String add_info_url;
#Override
protected void onPreExecute() {
list=new ArrayList<>();
add_info_url = "http://192.168.2.6/Deal%20Engine/editdetails.php";
}
#Override
protected void onPostExecute(String result) {
listItems.addAll(list);
Toast.makeText(getApplicationContext(), result, Toast.LENGTH_SHORT).show();
//SharedPreferences sp = getSharedPreferences("Login",Context.MODE_PRIVATE);
Intent i = new Intent(User.this, EditDetails.class);
startActivity(i);
}
#Override
protected String doInBackground(String... args) {
BufferedReader reader = null;
try {
URL url = new URL(add_info_url);
HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
httpURLConnection.setRequestMethod("POST");
httpURLConnection.setDoOutput(true);
OutputStream outputStream = httpURLConnection.getOutputStream();
BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(outputStream, "UTF-8"));
String dataString = URLEncoder.encode("id", "UTF-8") + "=" + URLEncoder.encode(String.valueOf(id), "UTF-8");
Log.d("id", String.valueOf(id));
bufferedWriter.write(dataString);
Log.d("Result", dataString);
bufferedWriter.flush();
bufferedWriter.close();
outputStream.close();
InputStream inputStream = httpURLConnection.getInputStream();
reader = new BufferedReader(new InputStreamReader(inputStream));
StringBuffer buffer = new StringBuffer();
String line = "";
while ((line = reader.readLine()) != null) {
buffer.append(line);
}
String finalJson = buffer.toString();
Log.d("String", finalJson);
JSONObject parentObject = new JSONObject(finalJson);
JSONArray parentArray = parentObject.getJSONArray("user");
StringBuffer finalBufferedData = new StringBuffer();
for (int i = 0; i < parentArray.length(); i++) {
JSONObject finalObject = parentArray.getJSONObject(i);
int status_code = finalObject.getInt("status_code");
String status_desc = finalObject.getString("status_desc");
String user_id = finalObject.getString("user_id");
int id = finalObject.getInt("id");
String name=finalObject.getString("name");
String pass= finalObject.getString("pass");
String location = finalObject.getString("location");
String cards=finalObject.getString("cards");
String category= finalObject.getString("category");
String wallet = finalObject.getString("wallet");
String operator=finalObject.getString("operator");
String loyaltyProgram= finalObject.getString("loyaltyProgram");
String membership= finalObject.getString("membership");
JSONObject walletArrayObject = new JSONObject(finalObject.getString("wallet_array"));
JSONArray walletArray = walletArrayObject.getJSONArray("wallets");
Log.d("Arraysize",String.valueOf(walletArray));
for(int j =0;j<walletArray.length();j++)
{
JSONObject walletObject = walletArray.getJSONObject(j);
list.add(new Populate(String.valueOf(walletObject.getInt("id")),walletObject.getString("wallet_name")));
}
sp = getSharedPreferences("Login",Context.MODE_PRIVATE);
editor=sp.edit();
editor.putString("name",name);
editor.putString("pass",pass);
editor.putInt("id",id);
editor.putString("location",location);
editor.putString("cards",cards);
editor.putString("category",category);
editor.putString("wallet",wallet);
editor.putString("operator",operator);
editor.putString("wallets",String.valueOf(list));
editor.putString("loyaltyProgram",loyaltyProgram);
editor.putString("membership",membership);
editor.commit();
finalBufferedData.append(status_code + " - " + status_desc + " -" + user_id + " -"+id + " -"+name+ " -"+list +"\n");
}
inputStream.close();
httpURLConnection.disconnect();
Log.d("Result", dataString);
return finalBufferedData.toString();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onProgressUpdate(Void... values) {
super.onProgressUpdate(values);
}
}
}
error I am getting
06-29 12:53:08.015 28974-28988/com.example.tanmayjain.twowaycommunication D/String: {"user":[{"status_code":"1","status_desc":"Success","user_id":"482","id":"26","name":"tanmay ","pass":"a006b22f887f7d922bafa4c8186ccafd","location":"Ahmedabad","cards":"ICICI Bank","category":"Platinum","wallet":"","operator":"Vodafone","loyaltyProgram":"Any","membership":"All Time","wallet_array":"{\"wallets\":[{\"1\":[\"Paytm\"],\"2\":[\"Freecharge\"],\"3\":[\"Mobikwik\"],\"4\":[\"PayUmoney\"],\"5\":[\"CitrusCash\"],\"6\":[\"Airtel Money\"],\"7\":[\"Oxigen Wallet\"],\"8\":[\"OLAMoney\"],\"9\":[\"HDFC PayZapp\"],\"10\":[\"Chillr by HDFC\"],\"11\":[\"Pockets by ICICI bank\"],\"12\":[\"JioMoney\"],\"13\":[\"SBI Buddy\"],\"14\":[\"mRupee\"],\"15\":[\"Itzcash\"]}]}"}]}
06-29 12:53:08.015 28974-28988/com.example.tanmayjain.twowaycommunication D/Arraysize: [{"1":["Paytm"],"2":["Freecharge"],"3":["Mobikwik"],"4":["PayUmoney"],"5":["CitrusCash"],"6":["Airtel Money"],"7":["Oxigen Wallet"],"8":["OLAMoney"],"9":["HDFC PayZapp"],"10":["Chillr by HDFC"],"11":["Pockets by ICICI bank"],"12":["JioMoney"],"13":["SBI Buddy"],"14":["mRupee"],"15":["Itzcash"]}]
06-29 12:53:08.016 28974-28988/com.example.tanmayjain.twowaycommunication W/System.err: org.json.JSONException: No value for id
06-29 12:53:08.016 28974-28988/com.example.tanmayjain.twowaycommunication W/System.err: at org.json.JSONObject.get(JSONObject.java:389)
06-29 12:53:08.016 28974-28988/com.example.tanmayjain.twowaycommunication W/System.err: at org.json.JSONObject.getInt(JSONObject.java:478)
06-29 12:53:08.016 28974-28988/com.example.tanmayjain.twowaycommunication W/System.err: at com.example.tanmayjain.twowaycommunication.User$BackgroundTask.doInBackground(User.java:167)
06-29 12:53:08.017 28974-28988/com.example.tanmayjain.twowaycommunication W/System.err: at com.example.tanmayjain.twowaycommunication.User$BackgroundTask.doInBackground(User.java:85)
06-29 12:53:08.017 28974-28988/com.example.tanmayjain.twowaycommunication W/System.err: at android.os.AsyncTask$2.call(AsyncTask.java:295)
I want to fetch id and wallet name from the array displayed in array size but i am getting this error.
Your json is wrong, because your walletObject contains this:
{
"wallets": [{
"1": ["Paytm"],
"2": ["Freecharge"],
"3": ["Mobikwik"],
"4": ["PayUmoney"],
"5": ["CitrusCash"],
"6": ["Airtel Money"],
"7": ["Oxigen Wallet"],
"8": ["OLAMoney"],
"9": ["HDFC PayZapp"],
"10": ["Chillr by HDFC"],
"11": ["Pockets by ICICI bank"],
"12": ["JioMoney"],
"13": ["SBI Buddy"],
"14": ["mRupee"],
"15": ["Itzcash"]
}]
}
You got the error because you would like to get the value of id property, but your json doesn't contains id field.
Your json has more problems:
1. send an object instead of array (wallet_array)
2. change your wallet object structure
I think you should use this json structure:
{
"user": [{
"status_code": "1",
"status_desc": "Success",
"user_id": "482",
"id": "26",
"name": "tanmay ",
"pass": "a006b22f887f7d922bafa4c8186ccafd",
"location": "Ahmedabad",
"cards": "ICICI Bank",
"category": "Platinum",
"wallet": "",
"operator": "Vodafone",
"loyaltyProgram": "Any",
"membership": "All Time",
"wallet_array": [{
"id": 1,
"name": "Paytm"
},
{
"id": 2,
"name": "Freecharge"
},
{
"id": 3,
"name": "Mobikwik"
},
{
"id": 4,
"name": "PayUmoney"
},
{
"id": 5,
"name": "CitrusCash"
},
{
"id": 6,
"name": "Airtel Money"
},
{
"id": 7,
"name": "Oxigen Wallet"
},
{
"id": 8,
"name": "OLAMoney"
},
{
"id": 9,
"name": "HDFC PayZapp"
}
]
}]
}

sort two array list simuntaneously in one activity

I am working on application in which i want one output as shown in below image.
for that i tried following code:
private ListView notification_listview;
private String BeauticianId="98";
private String serviceType="all";
private ArrayList<NameValuePair> params11;
ArrayList<MainArray_method> MainList;
MainArray_adapter main_adapter;
ArrayList<SubArray_method> SubList;
SubArray_adapter sub_adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
notification_listview = (ListView) findViewById(R.id.listView_notification);
}
#Override
public void onResume() {
super.onResume();
params11 = new ArrayList<NameValuePair>();
params11.add(new BasicNameValuePair("iBeauticianId", BeauticianId));
params11.add(new BasicNameValuePair("serviceType", serviceType));
new background().execute();
}
private class background extends AsyncTask<Void, Void, String> {
ProgressDialog pDialog = new ProgressDialog(MainActivity.this);
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog.setMessage("Please Wait...");
pDialog.setCancelable(false);
pDialog.show();
}
protected String doInBackground(Void... params) {
String obj;//new JSONArray();
try {
obj = getJSONFromUrl("http://52.26.35.210/api/web/v1/api-beautician/services", params11);
return obj;
} catch (Exception e) {
}
return null;
}
#Override
protected void onPostExecute(final String result) {
super.onPostExecute(result);
Log.e("Result", "" + result);
try {
JSONObject json = new JSONObject(result);
String status = json.getString("status");
Log.d("Status:", status);
String data = json.getString("data");
Log.d("Data:", data);
MainList = new ArrayList<MainArray_method>();
JSONArray MainArray = json.getJSONArray("data");
for (int i = 0; i < MainArray.length(); i++) {
JSONObject jsonObject = MainArray.getJSONObject(i);
String MainServiceId = jsonObject.getString("iMainServiceId");
Log.d("MainServiceId:", MainServiceId);
String MainService = jsonObject.getString("main");
Log.d("MainService:", MainService);
String sub = jsonObject.getString("sub");
Log.d("sub:", sub);
SubList = new ArrayList<SubArray_method>();
JSONArray SubArray = jsonObject.getJSONArray("sub");
for (int j = 0; j < SubArray.length(); j++) {
/*JSONObject subjsonObject = SubArray.getJSONObject(j);*/
/*String SubServiceId = subjsonObject.getString("iSubServiceId");
Log.d("subserviceid:", SubServiceId);
String SubServiceName = subjsonObject.getString("vName");
Log.d("SubServiceName:", SubServiceName);
String SubServicePrice = subjsonObject.getString("fPrice");
Log.d("SubServicePrice:", SubServicePrice);
String SubServiceTime = subjsonObject.getString("vDuration");
Log.d("SubServiceTime:", SubServiceTime);*/
MainList.add(new MainArray_method(MainArray.getJSONObject(i).getString("iMainServiceId"),
MainArray.getJSONObject(i).getString("main")));
SubList.add(new SubArray_method(SubArray.getJSONObject(j).getString("iSubServiceId"),
SubArray.getJSONObject(j).getString("vName"),
SubArray.getJSONObject(j).getString("fPrice"),
SubArray.getJSONObject(j).getString("vDuration")));
}
}
if (main_adapter== null && sub_adapter == null)
{
main_adapter=new MainArray_adapter(getApplicationContext(),MainList);
notification_listview.setAdapter(main_adapter);
sub_adapter=new SubArray_adapter(getApplicationContext(),SubList);
notification_listview.setAdapter(sub_adapter);
} else {
sub_adapter.notifyDataSetChanged();
main_adapter.notifyDataSetChanged();
}
} catch (JSONException e1) {
e1.printStackTrace();
}
pDialog.dismiss();
}
public String getJSONFromUrl(String url, List<NameValuePair> params) {
InputStream is = null;
String json = "";
// Making HTTP request
try {
// defaultHttpClient
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
httpPost.setEntity(new UrlEncodedFormEntity(params));
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(
is, "iso-8859-1"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line);
//sb.append(line + "\n");
}
is.close();
json = sb.toString();
Log.e("JSON", json);
} catch (Exception e) {
Log.e("Buffer Error", "Error converting result " + e.toString());
}
return json;
}
}
but in this i just get two record of subarray.
What should i do to get output as shown in image.
Thanks in advance.
JSON response:
{
"status":1,
"data":[
{
"iMainServiceId":1,
"main":"NAILS",
"sub":[
{
"iSubServiceId":1,
"vName":"Manicure",
"fPrice":15,
"vDuration":"20 Minutes"
},
{
"iSubServiceId":2,
"vName":"Gel Manicure",
"fPrice":25,
"vDuration":"30 Minutes"
},
{
"iSubServiceId":5,
"vName":"Nail art ",
"fPrice":10,
"vDuration":"20 Minutes"
},
{
"iSubServiceId":6,
"vName":"Nail Pain ",
"fPrice":10,
"vDuration":"20 Minutes"
}
]
},
{
"iMainServiceId":2,
"main":"HAIR",
"sub":[
{
"iSubServiceId":3,
"vName":"Haircuts",
"fPrice":20,
"vDuration":"30 Minutes"
},
{
"iSubServiceId":4,
"vName":"Hair color",
"fPrice":50,
"vDuration":"60 Minutes"
},
{
"iSubServiceId":7,
"vName":"Textures",
"fPrice":20,
"vDuration":"30 Minutes"
},
{
"iSubServiceId":8,
"vName":"Treatments",
"fPrice":30,
"vDuration":"60 Minutes"
}
]
},
{
"iMainServiceId":3,
"main":"Face",
"sub":[
{
"iSubServiceId":9,
"vName":"Facials",
"fPrice":20,
"vDuration":"49 Minutes"
},
{
"iSubServiceId":10,
"vName":"Brow Bar",
"fPrice":40,
"vDuration":"49 Minutes"
},
{
"iSubServiceId":11,
"vName":"Makeup ",
"fPrice":40,
"vDuration":"49 Minutes"
}
]
},
{
"iMainServiceId":4,
"main":"Body",
"sub":[
{
"iSubServiceId":12,
"vName":"Hair Removal",
"fPrice":40,
"vDuration":"49 Minutes"
},
{
"iSubServiceId":13,
"vName":"Body Treatments",
"fPrice":30,
"vDuration":"30 Minutes"
}
]
}
]
}
and wt i get as enter image description hereoutput is:
for (int i = 0; i < MainArray.length(); i++) {
JSONObject jsonObject = MainArray.getJSONObject(i);
String MainServiceId = jsonObject.getString("iMainServiceId");
Log.d("MainServiceId:", MainServiceId);
String MainService = jsonObject.getString("main");
Log.d("MainService:", MainService);
String sub = jsonObject.getString("sub");
Log.d("sub:", sub);
SubList = new ArrayList<SubArray_method>();
JSONArray SubArray = jsonObject.getJSONArray("sub");
for (int j = 0; j < SubArray.length(); j++) {
/*JSONObject subjsonObject = SubArray.getJSONObject(j);*/
/*String SubServiceId = subjsonObject.getString("iSubServiceId");
Log.d("subserviceid:", SubServiceId);
String SubServiceName = subjsonObject.getString("vName");
Log.d("SubServiceName:", SubServiceName);
String SubServicePrice = subjsonObject.getString("fPrice");
Log.d("SubServicePrice:", SubServicePrice);
String SubServiceTime = subjsonObject.getString("vDuration");
Log.d("SubServiceTime:", SubServiceTime);*/
SubList.add(new SubArray_method(SubArray.getJSONObject(j).getString("iSubServiceId"),
SubArray.getJSONObject(j).getString("vName"),
SubArray.getJSONObject(j).getString("fPrice"),
SubArray.getJSONObject(j).getString("vDuration")));
}
// This should be in outer for loop<<---------------------<<<<<
MainList.add(new MainArray_method(MainArray.getJSONObject(i).getString("iMainServiceId"),
MainArray.getJSONObject(i).getString("main")));
}

How to fetch a data from the database mysql using asynctask?

While fetching data in TextView I am getting an error. I tried but its not working.
Error parsing data org.json.JSONException: End of input at character 0
Json
[{
"0": "1",
"cl_id": "1",
"1": "",
"cl_department": "",
"2": "3G COMMUNICATION",
"cl_pname": "3G COMMUNICATION",
"3": "NIRAJBHAI",
"cl_salesperson": "NIRAJBHAI",
"4": "",
"cl_oname": "",
"5": "MOHMADBHAI",
"cl_contact": "MOHMADBHAI",
"6": "JUBELY SHAK MARKET",
"cl_address": "JUBELY SHAK MARKET",
"7": "",
"cl_city": "",
"8": "360001",
"cl_pincode": "360001",
"9": "",
"cl_bdate": "",
"10": "",
"cl_adate": "",
"11": "",
"cl_opening": "",
"12": "9376052000",
"cl_cnumber": "9376052000",
"13": "",
"cl_wnumber": "",
"14": "",
"cl_email": "",
"15": "RT40848",
"cl_wodcode": "RT40848",
"16": "",
"cl_active": "",
"17": "",
"cl_saleman": "",
"18": "",
"cl_bank_name": "",
"19": "",
"cl_bank_city": "",
"20": "",
"cl_ifsc_code": "",
"21": "",
"cl_bank_ac_no": "",
"22": "",
"cl_bank_ac_holder": "",
"23": "",
"cl_pancard_no": "",
"24": "",
"cl_visiting_card": "",
"25": "ACTIVE",
"cl_status": "ACTIVE",
"26": "",
"cl_aread": "",
"27": "",
"cl_target": "",
"28": "",
"cl_archive": "",
"29": "",
"cl_remaining": "",
"30": "A1",
"cl_group": "A1",
"31": "Om",
"cl_category": "Om",
"32": "",
"cl_credit": ""
},
Here is my complete code,
Main.java
public class MainActivity extends Activity {
private WebView wv1;
InputStream is=null;
String result=null;
String line=null;
JSONObject jsonobject;
public static String DATA_URL = "http://10.0.2.2/portal/fetchwod.php";
JSONParser jParser = new JSONParser();
JSONArray ownerObj;
ArrayList<HashMap<String, String>> arraylist;
ArrayList<String> delivery_fetch = new ArrayList<String>();
String suid,uid,wt_wod_code1,wt_party1;
TextView abcd,abc1;
View view;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
new DownloadJSON().execute();
abcd =(TextView)findViewById(R.id.abc);
abc1 =(TextView)findViewById(R.id.abc1);
}
private class MyBrowser extends WebViewClient {
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url ) {
view.loadUrl(url);
String id = abcd.getText().toString().trim();
return true;
}
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
return super.onOptionsItemSelected(item);
}
private class DownloadJSON extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected Void doInBackground(Void... voids) {
try {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://10.0.2.2/portal/autocomplete.php");
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
is = entity.getContent();
Log.e("Pass 1", "connection success ");
} catch (Exception e) {
Log.e("Fail 1", e.toString());
Toast.makeText(getApplicationContext(), "Invalid IP Address", Toast.LENGTH_LONG).show();
}
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(is, "iso-8859-1"), 8);
StringBuilder sb = new StringBuilder();
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
result = sb.toString();
Log.e("Pass 2", "connection success ");
} catch (Exception e) {
Log.e("Fail 2", e.toString());
}
return null;
}
#Override
protected void onPostExecute(Void args) {
try {
JSONArray JA = new JSONArray(result);
JSONObject json = null;
final String[] str1 = new String[JA.length()];
for (int i = 0; i < JA.length(); i++) {
json = JA.getJSONObject(i);
str1[i] = json.getString("cl_pname");
}
final AutoCompleteTextView text = (AutoCompleteTextView) findViewById(R.id.autoCompleteTextView1);
final List<String> list = new ArrayList<String>();
for (int i = 0; i < str1.length; i++) {
list.add(str1[i]);
}
Collections.sort(list);
final ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>(getApplicationContext(), R.layout.my_list_item, list);
dataAdapter.setDropDownViewResource(android.R.layout.simple_list_item_1);
text.setThreshold(1);
text.setAdapter(dataAdapter);
text.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
wv1 = (WebView) findViewById(R.id.webView);
wv1.setWebViewClient(new MyBrowser());
wv1.loadUrl("http://10.0.2.2/portal/on_target.php?=cod");
wv1.getSettings().setLoadsImagesAutomatically(true);
wv1.getSettings().setJavaScriptEnabled(true);
wv1.setScrollBarStyle(View.SCROLLBARS_INSIDE_OVERLAY);
Toast.makeText(getApplicationContext(), (CharSequence) arg0.getItemAtPosition(arg2), Toast.LENGTH_LONG).show();
wt_wod_code1 = text.getText().toString();
wt_party1 = text.getText().toString();
abcd.setText(text.getText());
Log.d("wt_wod_code", wt_party1);
new getdata().execute();
}
});
} catch (Exception e) {
Log.e("Fail 3", e.toString());
}
}
}
private class getdata extends AsyncTask<Void, Void, Void> {
#Override
protected Void doInBackground(Void... voids) {
try {
String uid = abcd.getText().toString().trim();
arraylist = new ArrayList<HashMap<String, String>>();
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("cl_pname", uid));
JSONObject json = jParser.makeHttpRequest(DATA_URL, "GET", params);
int success1 = Integer.parseInt(json.getString("success4"));
Log.d("success4", json.toString());
if (success1 == 0) {
Snackbar.make(view, "Not Data Found", Snackbar.LENGTH_LONG).show();
}
if (success1 == 1) {
ownerObj = json.getJSONArray("Ordera");
for (int i = 0; i < ownerObj.length(); i++) {
jsonobject = ownerObj.getJSONObject(i);
delivery_fetch.add(jsonobject.getString("cl_wodcode"));
}
}
}
catch(Exception e)
{
}
return null;
}
#Override
protected void onPostExecute(Void args) {
abc1 =(TextView)findViewById(R.id.abc1);
abc1.setText(delivery_fetch.toString());
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
}
Here is my Logcat,
com.example.sachin.addvisit E/Pass 1: connection success
com.example.sachin.addvisit E/Pass 2: connection success
com.example.sachin.addvisit D/wt_wod_code: D.K. METAL
com.example.sachin.addvisit D/response: {"success":1,"Ordera":[{"cl_wodcode":"RT34705","cl_pname":"D.K. METAL"}]}
com.example.sachin.addvisit E/Buffer Error: Error converting result java.lang.NullPointerException: lock == null
com.example.sachin.addvisit E/JSON Parser: Error parsing data org.json.JSONException: End of input at character 0 of
The data is displaying in the logcat but not fetching in the TextView.
I validated my JSON online an it looks alright.
i don't know where's the problem is please help me out.
if required i'll post my API too..
Parse the JSON as follows,
final String[] str1 = new String[JA.length()];
final String[] str2 = new String[JA.length()];
for (int i = 0; i < JA.length(); i++) {
json = JA.getJSONObject(i);
str1[i] = json.getString("cl_pname");
str2[i] = json.getString("cl_wodcode");
}
Inside the OnItemClickListener,
text.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
String selected_cl_pname = (String) parent.getItemAtPosition(position);
int index = Arrays.asList(str1).indexOf(selected_cl_pname);
String selected_cl_wodcode = str2[index];
abc1.setText(selected_cl_wodcode);
// rest of your code
}
});
I recommend to use a model class and use GSON to parse the JSON.

How do I match data by ID's in Android using JSON?

I have two fragments, one shows a program list and one shows a course list. How do I get the selected program from the mainactivity to only show the corresponding course description? They match by ID. Currently, when I click on a program, the whole course list shows up instead of the corresponding course.
MainActivity Fragment (shows all data in JSON file):
ProgramAdapter programAdapter;
#Override
public void onListItemClick(ListView l, View v, int position, long id) {
super.onListItemClick(l, v, position, id);
ProgramDetail item = (ProgramDetail) getListAdapter().getItem(position);
Intent intent = new Intent(getActivity(), ProgramDetailActivity.class);
intent.putExtra(ProgramDetailActivity.EXTRA_ID, item.getId());
startActivity(intent);
}
#Override
public void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
programAdapter = new ProgramAdapter(getActivity());
setListAdapter(programAdapter);
setListShown(false);
new HttpAsyncTask().execute("https://gist.githubusercontent.com/kdotzenrod517/39bc7372759c762e33188fb1a6cbce5d/raw/a2baa28d19fd597be999c8fddb6b48c888cd33f4/gistfile1.txt");
}
private class HttpAsyncTask extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... params) {
Log.e("HttpAsyncTask", "doInBackground");
String result = "";
HttpURLConnection urlConnection = null;
try{
URL url = new URL(params[0]);
Log.e("HttpAsyncTask", params[0]);
urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setRequestProperty("Accept", "application/json");
InputStream inputStream = new BufferedInputStream(urlConnection.getInputStream());
Log.e("HttpAsyncTask", "getInputStream");
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
String s = "";
while ((s = reader.readLine()) != null){
result += s;
Log.e("HttpAsyncTask", result);
}
} catch (Exception e){
Log.e("HttpAsyncTask", "EXCEPTION: " + e.getMessage());
} finally {
if (urlConnection != null){
urlConnection.disconnect();
}
}
return result;
}
#Override
protected void onPostExecute(String s) {
Log.e("HttpAsyncTask", "entering onPostExecute");
try {
JSONArray jsonArray = new JSONArray(s);
final int length = jsonArray.length();
Log.i("HttpAsyncTask", "Number" + length);
List<ProgramDetail> items = new ArrayList<>();
for (int i=0; i < length; i++){
JSONObject jsonObject = jsonArray.getJSONObject(i);
items.add(new ProgramDetail(jsonObject.getString("name"),null,jsonObject.getLong("id")));
}
programAdapter.addAll(items);
programAdapter.notifyDataSetChanged();
setListShown(true);
} catch (JSONException e) {
}
}
}
}
CourseList Fragment (should only show matching JSON data by ID)
`
protected void onPostExecute(String s) {
Log.e("HttpAsyncTask", "entering onPostExecute");
try {
JSONArray jsonArray = new JSONArray(s);
final int length = jsonArray.length();
Log.i("HttpAsyncTask", "Number" + length);
List<ProgramDetail> item = new ArrayList<>();
for (int i=0; i < length; i++){
JSONObject jsonObject = jsonArray.getJSONObject(i);
item.add(new ProgramDetail(jsonObject.getString("name"), null, jsonObject.getLong("id")));
}
programAdapter.addAll(item);
programAdapter.notifyDataSetChanged();
setListShown(true);
} catch (JSONException e) {
}
Program List
[
{
"id": "0",
"name": "Intro to Android"
},
{
"id": "1",
"name": "Advanced Android"
},
{
"id": "2",
"name": "Intro to Java"
},
{
"id": "3",
"name": "Advanced Java"
},
{
"id": "4",
"name": "Intro to Data Science"
}
]
Course List JSON
{
"id": "0",
"name": "Welcome to Android!"
},
{
"id": "1",
"name": "Enterprise level Android Dev"
},
{
"id": "2",
"name": "Welcome to Java!"
},
{
"id": "3",
"name": "Enterprise Level Java"
},
{
"id": "4",
"name": "Welcome to Data Science!"
}

Error with a JSON parser and a listview

I made an app for my website which takes som information from my website brainstorm.web44.net
(those posts are just for testing!) and puts them in a custom listview.
Here is the java code:
public class MainActivity extends ListActivity {
JSONArray titles;
HttpClient client;
final static String URL = "http://brainstorm.net.com/?json=1";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
client = new DefaultHttpClient();
String[] from = new String[] { "Title", "Description" };
int[] to = new int[] { R.id.txtTitle, R.id.txtContent };
List<HashMap<String, Object>> fillMaps;
try {
fillMaps = setContentAndTitle(new Read().execute("title").get(),
new Read().execute("content").get());
SimpleAdapter adapter = new SimpleAdapter(this, fillMaps,
R.layout.list_item, from, to);
setListAdapter(adapter);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ExecutionException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
private List<HashMap<String, Object>> setContentAndTitle(String[] titles,
String[] descriptions) {
// TODO Auto-generated method stub
List<HashMap<String, Object>> fillMaps = new ArrayList<HashMap<String, Object>>();
for (int number = 0; number < titles.length; number++) {
HashMap<String, Object> map = new HashMap<String, Object>();
map.put("Title", titles[number]);
map.put("Description", descriptions[number]);
fillMaps.add(map);
}
return fillMaps;
}
public JSONArray Title() throws ClientProtocolException, IOException,
JSONException {
StringBuilder url = new StringBuilder(URL);
HttpGet get = new HttpGet(url.toString());
HttpResponse r = client.execute(get);
int status = r.getStatusLine().getStatusCode();
if (status == 200) {
HttpEntity e = r.getEntity();
String data = EntityUtils.toString(e);
JSONArray brainstorm = new JSONArray(data);
return brainstorm;
} else {
return null;
}
}
public class Read extends AsyncTask<String, Integer, String[]> {
#Override
protected String[] doInBackground(String... arg0) {
// TODO Auto-generated method stub
List<String> titlesArray = new ArrayList<String>();
try {
titles = Title();
for (int i = 0; i < titles.length(); i++) {
JSONObject title = titles.getJSONObject(i);
String s = title.getString("title");
titlesArray.add(s);
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
String[] arr = toStringArray(titlesArray.toArray());
return arr;
}
private String[] toStringArray(Object[] array) {
// TODO Auto-generated method stub
String[] arr = new String[array.length];
for(int i=0;i<arr.length;i++){
arr[i]=array[i].toString();
}
return null;
}
}
}
Logcat :
06-27 18:11:32.768: E/AndroidRuntime(1809): Caused by: java.lang.NullPointerException
06-27 18:11:32.768: E/AndroidRuntime(1809): at com.tendariusprod.brainstorm.MainActivity.setContentAndTitle(MainActivity.java:64)
06-27 18:11:32.768: E/AndroidRuntime(1809): at com.tendariusprod.brainstorm.MainActivity.onCreate(MainActivity.java:43)
Json :
{
"status": "ok",
"count": 2,
"count_total": 2,
"pages": 1,
"posts": [
{
"id": 17,
"type": "post",
"slug": "json-parser",
"url": "http://brainstorm.web44.net/?p=17",
"status": "publish",
"title": "JSON Parser",
"title_plain": "JSON Parser",
"content": "<p>JSON Parser!</p>\n",
"excerpt": "<p>JSON Parser!</p>\n",
"date": "2013-06-27 09:02:55",
"modified": "2013-06-27 09:02:55",
"categories": [],
"tags": [],
"author": {
"id": 1,
"slug": "admin",
"name": "admin",
"first_name": "",
"last_name": "",
"nickname": "admin",
"url": "",
"description": ""
},
"comments": [],
"attachments": [],
"comment_count": 0,
"comment_status": "open",
"custom_fields": {
"single_layout": [
"0"
]
}
},
{
"id": 14,
"type": "post",
"slug": "supermoon-ready-to-be-seen",
"url": "http://brainstorm.web44.net/?p=14",
"status": "publish",
"title": "Supermoon ready to be seen!",
"title_plain": "Supermoon ready to be seen!",
"content": "<p>You will see the moon in its all splendore tonight!</p>\n",
"excerpt": "<p>You will see the moon in its all splendore tonight!</p>\n",
"date": "2013-06-26 16:56:19",
"modified": "2013-06-26 17:18:11",
"categories": [],
"tags": [],
"author": {
"id": 1,
"slug": "admin",
"name": "admin",
"first_name": "",
"last_name": "",
"nickname": "admin",
"url": "",
"description": ""
},
"comments": [],
"attachments": [],
"comment_count": 0,
"comment_status": "open",
"custom_fields": {
"single_layout": [
"0"
]
}
}
]
}
Edit: this is a new code for the asynctask:
public class Read extends AsyncTask<Void, Void, Void> {
#Override
protected Void doInBackground(Void... arg0) {
// TODO Auto-generated method stub
try {
StringBuilder url = new StringBuilder(URL);
HttpGet get = new HttpGet(url.toString());
HttpResponse r = client.execute(get);
int status = r.getStatusLine().getStatusCode();
if (status == 200) {
HttpEntity e = r.getEntity();
String data = EntityUtils.toString(e);
JSONObject o =new JSONObject(data);
titles = new JSONArray(o.getString("posts"));
} else {
Toast t = Toast.makeText(MainActivity.this, "Error", Toast.LENGTH_LONG);
t.show();
}
for (int i = 0; i < titles.length(); i++) {
JSONObject title = titles.getJSONObject(i);
String s = title.getString("title");
String b = title.getString("content");
descArray.add(b);
titlesArray.add(s);
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
List<HashMap<String, Object>> fillMaps = new ArrayList<HashMap<String, Object>>();
String[] arr1 = toStringArray(titlesArray.toArray()), arr2 = toStringArray(descArray
.toArray());
for (int number = 0; number < arr1.length; number++) {
HashMap<String, Object> map = new HashMap<String, Object>();
map.put("Title", arr1[number]);
map.put("Description", arr2[number]);
fillMaps.add(map);
String[] from = new String[] { "Title", "Description" };
int[] to = new int[] { R.id.txtTitle, R.id.txtContent };
SimpleAdapter adapter = new SimpleAdapter(MainActivity.this, fillMaps, R.layout.list_item, from, to);
setListAdapter(adapter);
}
}
You can parse with a single asynctask and display data in listview. I have used custom listview to display the content and title.
public class MainActivity extends ListActivity {
JSONArray titles;
HttpClient client;
ProgressDialog pd;
final static String URL = "http://brainstorm.web44.net/?json=1";
ArrayList<String> title = new ArrayList<String>();
ArrayList<String> content = new ArrayList<String>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
pd = new ProgressDialog(MainActivity.this);
pd.setMessage("Loading...");
client = new DefaultHttpClient();
new Read().execute();
}
public class Read extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
// TODO Auto-generated method stub
pd.show();
super.onPreExecute();
}
#Override
protected void onPostExecute(Void result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
pd.dismiss();
CustomAdapter cus = new CustomAdapter();
setListAdapter(cus);
}
#Override
protected Void doInBackground(Void... params) {
// TODO Auto-generated method stub
try {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(URL);
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
InputStream is = entity.getContent();
BufferedReader reader = new BufferedReader(new InputStreamReader(is,"iso-8859-1"),8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
String result=sb.toString();
try {
JSONObject jsono = new JSONObject(result);
JSONArray jsonarray = new JSONArray(jsono.getString("posts"));
for(int i=0;i<jsonarray.length();i++)
{
JSONObject job1 = (JSONObject) jsonarray.get(i);
String titl = job1.getString("title");
String con = job1.getString("content");
title.add(titl);
content.add(con) ;
Log.i("......", titl);
Log.i("......", con);
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} catch (IllegalStateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
}
class CustomAdapter extends BaseAdapter
{
LayoutInflater mInflater;
public CustomAdapter()
{
mInflater = LayoutInflater.from(MainActivity.this);
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return title.size();
}
#Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return null;
}
#Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return 0;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
ViewHolder holder;
if (convertView == null) {
convertView = mInflater.inflate(R.layout.list_item,
parent, false);
holder = new ViewHolder();
holder.tv1 = (TextView) convertView.findViewById(R.id.textView1);
holder.tv2 = (TextView) convertView.findViewById(R.id.textView2);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
holder.tv1.setText(title.get(position));
holder.tv2.setText(content.get(position));
return convertView;
}
}
static class ViewHolder
{
TextView tv1,tv2;
}
}
list_itemt.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
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:text="TextView" />
<TextView
android:id="#+id/textView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/textView1"
android:layout_below="#+id/textView1"
android:layout_marginTop="22dp"
android:text="TextView" />
</RelativeLayout>
Snap shot

Categories

Resources