Data is not fetched through json parsing. I want to fetch data from url and just set it to a textview. please help
private static final String URL_PRODUCTS = "http://ebeautyapp.com/experts/getContactUs.php";
//method for json parcing
private void loadData() {
StringRequest stringRequest = new StringRequest(Request.Method.GET, URL_PRODUCTS,
new Response.Listener < String > () {
#Override
public void onResponse(String response) {
try {
JSONObject jObj = new JSONObject(response);
String result = jObj.getString("result");
if (result.equals("success")) {
JSONArray jsonArray = jObj.getJSONArray("data");
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObject = jsonArray.getJSONObject(i);
String contact_id = jsonObject.getString("contact_id");
String fullname = jsonObject.getString("fullname");
String moble1 = jsonObject.getString("moble1");
String mobileno2 = jsonObject.getString("mobileno2");
String profile_pic = jsonObject.getString("profile_pic");
String address = jsonObject.getString("address");
String about_us = jsonObject.getString("about_us");
fulllnames.setText(fullname);
mobilenos.setText(moble1);
}
} else {
String status = jObj.getString("status");
Toast.makeText(getApplicationContext(), "" + status, Toast.LENGTH_SHORT).show();
}
} catch (JSONException e) {
// JSON error
e.printStackTrace();
Toast.makeText(getApplicationContext(), "Json error: " + e.getMessage(), Toast.LENGTH_LONG).show();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
});
//adding our stringrequest to queue
Volley.newRequestQueue(this).add(stringRequest);
}
Using this I have got the response from the server. Hope this will solve your problem.
class RetrieveFeedTask extends AsyncTask<Void, Void, String> {
protected void onPreExecute() {
// responseView.setText("");
}
protected String doInBackground(Void... urls) {
String API_URL = "http://ebeautyapp.com/experts/getContactUs.php";
// Do some validation here
try {
URL url = new URL(API_URL);
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
try {
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(urlConnection.getInputStream()));
StringBuilder stringBuilder = new StringBuilder();
String line;
while ((line = bufferedReader.readLine()) != null) {
stringBuilder.append(line).append("\n");
}
bufferedReader.close();
return stringBuilder.toString();
}
finally{
urlConnection.disconnect();
}
}
catch(Exception e) {
Log.e("ERROR", e.getMessage(), e);
return null;
}
}
protected void onPostExecute(String response) {
if(response == null) {
response = "THERE WAS AN ERROR";
}
// progressBar.setVisibility(View.GONE);
Log.i("INFO", response);
// responseView.setText(response);
// parseJsonData(response);
}
JSON parsing
private void jsonParsing(String response){
try {
JSONObject jObj = new JSONObject(response);
String result = jObj.getString("result");
if (result.equals("success")) {
JSONArray jsonArray = jObj.getJSONArray("data");
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObject = jsonArray.getJSONObject(i);
String contact_id = jsonObject.getString("contact_id");
String fullname = jsonObject.getString("fullname");
String moble1 = jsonObject.getString("moble1");
String mobileno2 = jsonObject.getString("mobileno2");
String profile_pic = jsonObject.getString("profile_pic");
String address = jsonObject.getString("address");
String about_us = jsonObject.getString("about_us");
fulllnames.setText(fullname);
mobilenos.setText(moble1);
}
} else {
String status = jObj.getString("status");
Toast.makeText(getApplicationContext(), "" + status, Toast.LENGTH_SHORT).show();
}
} catch (JSONException e) {
// JSON error
e.printStackTrace();
Toast.makeText(getApplicationContext(), "Json error: " + e.getMessage(), Toast.LENGTH_LONG).show();
}
}
}
And use this task as simple by using this
new RetrieveFeedTask().execute();
Related
When I run the following code It does not display data.It shows the following error message:
2019-11-16 14:40:19.149 17562-17585/com.example.jsonparsing E/MainActivity: Response from url: <html>
<head><title>301 Moved Permanently</title></head>
<body bgcolor="white">
<center><h1>301 Moved Permanently</h1></center>
<hr><center>nginx/1.10.3 (Ubuntu)</center>
</body>
</html>
2019-11-16 14:40:19.149 17562-17585/com.example.jsonparsing E/MainActivity: Json parsing error: Value jsonStr of type java.lang.String cannot be converted to JSONObject
2019-11-16 14:40:19.164 17562-17589/com.example.jsonparsing I/OpenGLRenderer: Initialized EGL, version 1.4
2019-11-16 14:40:19.172 17562-17589/com.example.jsonparsing W/OpenGLRenderer: Failed to choose config with EGL_SWAP_BEHAVIOR_PRESERVED, retrying without...
MainActivity:
public class MainActivity extends AppCompatActivity {
private ArrayAdapter adapter;
public static final String TAG = MainActivity.class.getSimpleName();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
RecyclerView recyclerView = findViewById(R.id.recyclerview);
adapter = new ArrayAdapter(getApplicationContext());
recyclerView.setAdapter(adapter);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
new getContacts().execute();
}
class getContacts extends AsyncTask<Void, Void, List<HashMap<String, String>>> {
#Override
protected void onPreExecute() {
super.onPreExecute();
Toast.makeText(getApplicationContext(), "JSON Data is" +
" downloading", Toast.LENGTH_LONG).show();
}
#Override
protected List<HashMap<String, String>> doInBackground(Void... Void) {
HttpHandler sh = new HttpHandler();
String url = "http://api.androidhive.info/contacts/";
String jsonStr = sh.makeServiceCall(url);
Log.e(TAG, "Response from url: " + jsonStr);
if (jsonStr != null) {
try {
JSONObject jsonObject = new JSONObject("jsonStr");
List<HashMap<String, String>> contactList = new ArrayList<>();
JSONArray contacts = jsonObject.getJSONArray("contacts");
for (int i = 0; i < contacts.length(); i++) {
JSONObject c = contacts.getJSONObject(i);
String id = c.getString("id");
String name = c.getString("name");
String email = c.getString("email");
String address = c.getString("address");
String gender = c.getString("gender");
JSONObject phone = c.getJSONObject("phone");
String mobile = phone.getString("mobile");
String home = phone.getString("home");
String office = phone.getString("office");
HashMap<String, String> contact = new HashMap<>();
contact.put("id", id);
contact.put("name", name);
contact.put("email", email);
contact.put("mobile", mobile);
contactList.add(contact);
}
return contactList;
} catch (final JSONException e) {
Log.e(TAG, "Json parsing error: " + e.getMessage());
runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(getApplicationContext(), "Json parsing error: "
+ e.getMessage(), Toast.LENGTH_LONG).show();
}
});
}
} else {
Log.e(TAG, "Couldn't get json from server.");
runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(getApplicationContext(), "Couldn't get json from server. Check LogCat for possible errors",
Toast.LENGTH_LONG).show();
}
});
}
return null;
}
#Override
protected void onPostExecute(List<HashMap<String, String>> result) {
super.onPostExecute(result);
if (result != null) {
adapter.add(result);
adapter.notifyDataSetChanged();
}
}
}
}
HttpHandler:
class HttpHandler {
private static final String TAG = HttpHandler.class.getSimpleName();
HttpHandler() {
}
String makeServiceCall(String reqUrl){
String response = null;
try {
URL url = new URL(reqUrl);
HttpURLConnection conn =(HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
InputStream in = new BufferedInputStream(conn.getInputStream());
response = convertStreamToString(in);
}catch (MalformedURLException e){
Log.e(TAG,"MalformException: " + e.getMessage());
}catch (ProtocolException e){
Log.e(TAG,"ProtocolException: " + e.getMessage());
}catch (IOException e){
Log.e(TAG, "IOException: " + e.getMessage());
}
return response;
}
private String convertStreamToString(InputStream is){
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
StringBuilder sb = new StringBuilder();
String line;
try {
while ((line = reader.readLine()) != null) {
sb.append(line).append("\n");
}
is.close();
}catch (IOException e){
e.printStackTrace();
}finally {
try {
is.close();
}catch (IOException e){
e.printStackTrace();
}
}
return sb.toString();
}
I can parse json from a url in this way:
String link1 = "http://www.url.com/test1.json";
String link2 = "http://www.url.com/test2.json";
private void fetchMovies() {
String url = link1;
JsonArrayRequest req = new JsonArrayRequest(url,
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
if (response.length() > 0) {
for (int i = 0; i < response.length(); i++) {
try {
JSONObject movieObj = response.getJSONObject(i);
int rank = movieObj.getInt("rank");
String title = movieObj.getString("title");
Movie m = new Movie(rank, title);
movieList.add(0, m);
} catch (JSONException e) {
}
}
adapter.notifyDataSetChanged();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(getApplicationContext(), error.getMessage(), Toast.LENGTH_LONG).show();
}
});
MyApplication.getInstance().addToRequestQueue(req);
}
I want to parse my json from multiple url.
I want to parse url1 and url2 at the same time.
How can I do that?
I created a class MyAsyncTask, this class receive the URL's list and the context activity. Guide yourself with the sample code.
public class MyAsyncTask extends AsyncTask<Void, Void, List<JSONObject>> {
private Activity activity;
private List<String> urls;
public MyAsyncTask(Activity activity, List<String> urls) {
this.urls = urls;
this.activity = activity;
}
#Override
protected List<JSONObject> doInBackground(Void... voids) {
HttpURLConnection connection = null;
BufferedReader reader = null;
List<JSONObject> jsonURls = new ArrayList<>();
try{
for (String url : urls) {
URL link = new URL(url);
connection = (HttpURLConnection) link.openConnection();
connection.setRequestProperty("Content-Type", "application/json");
connection.setRequestMethod("GET");
connection.connect();
reader = new BufferedReader(new InputStreamReader(connection.getInputStream(), "UTF-8"));
String line = null;
StringBuilder sb = new StringBuilder();
while ((line = reader.readLine()) != null)
sb.append(line);
reader.close();
JSONObject jsonResult = new JSONObject(sb.toString());
jsonURls.add(jsonResult);
}
} catch (MalformedURLException e) {
e.printStackTrace();
Toast.makeText(activity, "URL error", Toast.LENGTH_SHORT).show();
} catch (IOException e) {
e.printStackTrace();
Toast.makeText(activity, "Connection error", Toast.LENGTH_SHORT).show();
} catch (JSONException e) {
e.printStackTrace();
Toast.makeText(activity, "JSON Parsing error", Toast.LENGTH_SHORT).show();
}
return jsonURls;
}
#Override
protected void onPostExecute(List<JSONObject> jsonObjects) {
super.onPostExecute(jsonObjects);
// Process your JSONs
}
}
For to call it, you should do the following (Within your activity):
List<String> urls = new ArrayList<>();
urls.add("https://jsonplaceholder.typicode.com/posts/1");
MyAsyncTask myAsyncTask = new MyAsyncTask(MyActivity.this, urls);
myAsyncTask.execute();
The processing of the JSONs, you must in the PostExecute method.
Don't forget add internet permissions.
you can simple add your urls into the arraylist and parse the urls through a loop.
Arralist<String> arraylist = new Arraylist;
arraylist.add(link1);
arralist.add(link2);
private void fetchMovies() {
int x = arralist.size();
for(int i = 0;i<x;i++)
{ JsonArrayRequest req = new JsonArrayRequest(arralist.get(i),
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
if (response.length() > 0) {
for (int i = 0; i < response.length(); i++) {
try {
JSONObject movieObj = response.getJSONObject(i);
int rank = movieObj.getInt("rank");
String title = movieObj.getString("title");
Movie m = new Movie(rank, title);
movieList.add(0, m);
} catch (JSONException e) {
}
}
adapter.notifyDataSetChanged();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(getApplicationContext(), error.getMessage(), Toast.LENGTH_LONG).show();
}
});
MyApplication.getInstance().addToRequestQueue(req);
}}
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")));
}
I want develop android application for one website. I read website posts from json and show its in RecyclerView every 10 posts.
I can show title, description and thumbnail. but i want show medium from thumbnail_images instance of thumbnail. I don't know how to read images from medium ?!
My Json Link : Link
AsyncTaskCodes:
public class MainDataInfo {
private Context mContext;
private String ServerAddress = ServerIP.getIP();
public void getMainDataInfo(Context context) {
mContext = context;
new getInfo().execute(ServerAddress + "page=1");
}
private class getInfo extends AsyncTask<String, Void, String> {
EventBus bus = EventBus.getDefault();
private String ou_response;
private List<MainDataModel> infoModels;
#Override
protected void onPreExecute() {
CustomProcessDialog.createAndShow(mContext);
infoModels = new ArrayList<>();
}
#Override
protected String doInBackground(String... params) {
OkHttpClient client = new OkHttpClient();
Request request = new Request.Builder()
.url(ServerAddress + "page=1")
.build();
Response response;
try {
response = client.newCall(request).execute();
ou_response = response.body().string();
response.body().close();
if (ou_response != null) {
try {
JSONObject postObj = new JSONObject(ou_response);
JSONArray postsArray = postObj.getJSONArray("posts");
infoModels = new ArrayList<>();
for (int i = 0; i <= infoModels.size(); i++) {
JSONObject postObject = (JSONObject) postsArray.get(i);
int id = postObject.getInt("id");
String title = postObject.getString("title");
Log.d("Data", "Post id: " + id);
Log.d("Data", "Post title: " + title);
//Use the title and id as per your requirement
infoModels.add(new MainDataModel(
postObject.getInt("id"),
postObject.getString("title"),
postObject.getString("content"),
postObject.getString("thumbnail")));
}
} catch (JSONException e) {
e.printStackTrace();
}
}
} catch (IOException e) {
e.printStackTrace();
}
return ou_response;
}
#Override
protected void onPostExecute(String result) {
CustomProcessDialog.dissmis();
if (result != null) {
bus.post(infoModels);
}
}
}
}
How can set images from medium ? thanks all <3
try {
JSONObject postObj = new JSONObject(ou_response);
JSONArray postsArray = postObj.getJSONArray("posts");
for (int i= 0; i < postsArray.length(); i++){
JSONObject postObject = postsArray.getJSONObject(i);
int id = postObject.getInt("id");
String title = postObject.getString("title");
//get other data
JSONObject imageObj = postObject.getJSONObject("thumbnail_images");
JSONObject mediumObj = imageObj.getJSONObject("medium");
String mediumImage = mediumObj.getString("url");
Log.d("Data", "id: " + id);
Log.d("Data", "title: " + title);
//log other data
Log.d("Data", "the mediumObj url: " + mediumImage);
}
} catch (JSONException e) {
e.printStackTrace();
}
Hi friends i like to parse the json from url and also like to elimate the null values field and only show the object which has value if anyone known syntax for that means please guide me thanks in advance.
JSON Structure
{
"daftar_rs": [
{
"Name": "exe1",
"URL": "http://samir-mangroliya.blogspot.in/p/android-json-parsing-tutorial.html"
},
{
"Name": "exe2",
"URL": "https://code.google.com/p/json-io/"
},
{
"Name": "exe3",
"URL": ""
},
{
"Name": "exe4",
"URL": "http://stackoverflow.com/questions/10964203/android-removing-jsonobject"
},
{
"Name": "exe5",
"URL": ""
},
{
"Name": "exe6",
"URL": ""
}
],
"success": 1
}
MainActivity
public class MainActivity extends Activity {
ListView lv;
List<String> titleCollection = new ArrayList<String>();
List<String> urlCollection = new ArrayList<String>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
lv = (ListView) findViewById(R.id.listView1);
// we will using AsyncTask during parsing
new AsyncTaskParseJson().execute();
lv.setOnItemClickListener(new OnItemClickListener(){
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
long arg3) {
// TODO Auto-generated method stub
String linkUrl = urlCollection.get(arg2);
Intent webViewIntent = new Intent(MainActivity.this, WebViewActivity.class);
webViewIntent.putExtra("url", linkUrl);
startActivity(webViewIntent);
}
});
}
public void loadContents()
{
ArrayAdapter<String> adapter =new ArrayAdapter<String>(getBaseContext(), android.R.layout.simple_list_item_1,titleCollection);
lv.setAdapter(adapter);
}
// you can make this class as another java file so it will be separated from your main activity.
public class AsyncTaskParseJson extends AsyncTask<String, String, String> {
final String TAG = "AsyncTaskParseJson.java";
// set your json string url here
String yourJsonStringUrl = "http://192.168.1.167/vinandrophp/vinex.php";
// contacts JSONArray
JSONArray dataJsonArr = null;
#Override
protected void onPreExecute() {}
#Override
protected String doInBackground(String... arg0) {
try {
// instantiate our json parser
JsonParser jParser = new JsonParser();
// get json string from url
JSONObject json = jParser.getJSONFromUrl(yourJsonStringUrl);
// loop through all users
for (int i = 0; i < dataJsonArr.length(); i++) {
JSONObject c = dataJsonArr.getJSONObject(i);
// Storing each json item in variable
titleCollection.add(c.getString("Name"));
urlCollection.add(c.getString("URL"));
// show the values in our logcat
Log.e(TAG, "Name: " + titleCollection
+ ", URL: " + urlCollection);
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(String strFromDoInBg) {
loadContents();
}
}
}
JsonParser.java
public class JsonParser {
final String TAG = "JsonParser.java";
static InputStream is = null;
static JSONObject jObj = null;
static String json = "";
public JSONObject getJSONFromUrl(String url) {
// make HTTP request
try {
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
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 + "n");
}
is.close();
json = sb.toString();
} catch (Exception e) {
Log.e(TAG, "Error converting result " + e.toString());
}
// try parse the string to a JSON object
try {
jObj = new JSONObject(json);
} catch (JSONException e) {
Log.e(TAG, "Error parsing data " + e.toString());
}
// return JSON String
return jObj;
}
}
Just check it inside your code.
String linkUrl = urlCollection.get(arg2);
if (linkUrl== null || linkUrl.equals("")){
// null
}
else{
// not null so put to extras and start intent
Intent webViewIntent = new Intent(MainActivity.this, WebViewActivity.class);
webViewIntent.putExtra("url", linkUrl);
startActivity(webViewIntent);
}
try below code
for (int i = 0; i < dataJsonArr.length(); i++)
{
JSONObject c = dataJsonArr.getJSONObject(i);
// Storing each json item in variable
String Name = c.getString("Name");
String Url = c.getString("URL")
if(!TextUtils.isEmpty(Name) && !TextUtil.isEmpty(Url))
{
titleCollection.add(Name);
urlCollection.add(Url));
}
// show the values in our logcat
Log.e(TAG, "Name: " + titleCollection + ", URL: " + urlCollection);
}
try below code:-
if(c.getString("URL").equals("") || c.isNULL("URL"))
{
// do nothing
}
else
{
titleCollection.add(c.getString("Name"));
urlCollection.add(c.getString("URL"));
}
Change for loop as
for (int i = 0; i < dataJsonArr.length(); i++) {
JSONObject c = dataJsonArr.getJSONObject(i);
// Storing each json item in variable
String name = c.getString("Name");
String url = c.getString("URL");
if(name != null && !(name.equals(""))
&& url != null && !(url.equals(""){
titleCollection.add(c.getString("Name"));
urlCollection.add(c.getString("URL"));
}
// show the values in our logcat
Log.e(TAG, "Name: " + titleCollection
+ ", URL: " + urlCollection);
}
Try replace keys and values with regular expression if the key is empty in the JsonParser class.
json=json.replaceAll("\\n",""); //you should do not have any new lines after commas
json=json.replaceAll(",\\W*\"\\w+\":\\W?(\"\"|null)","");