Android using rest api - android

How to post the data dynamically from the get method to post method
pls, help me to solve this issue.in the url1 I have to store the data
in DB when I used to select the email id the particular physician key
and the email id should be stored in DB
if (jsonString1 != null) {
try {
JSONObject jsonObject1 = new JSONObject(jsonString1);
// Getting JSON Array node
JSONArray contacts1 = jsonObject1.getJSONArray("physicianlist");
for (int i = 0; i < contacts1.length(); i++) {
JSONObject c = contacts1.getJSONObject(i);
String Name = c.getString("Name");
String Physician_Key = c.getString("Physician_Key");
myIntArray[i]=Physician_Key;
String Specialization = c.getString("Specialization");
String ProviderName = c.getString("ProviderName");
String EmailId = c.getString("EmailId");
String Location = c.getString("Location");
HashMap<String, String> phy = new HashMap<>();
// adding each child node to HashMap key => value
phy.put("Name", Name);
phy.put("Physician_Key", Physician_Key);
phy.put("Specialization", Specialization);
phy.put("ProviderName",ProviderName);
phy.put("EmailId",EmailId);
phy.put("Location",Location);
al.add(EmailId);
// adding contact to contact list
phyJsonList.add(phy);
}
} 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, "Could not get json from server.");
runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(getApplicationContext(),
"Could not get json from server.",
Toast.LENGTH_LONG)
.show();
}
});
}
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
// Dismiss the progress dialog
if (progressDialog.isShowing())
progressDialog.dismiss();
/**
* Updating parsed JSON data into ListView
* */
ListAdapter adapter1 = new SimpleAdapter(
MainActivity.this,phyJsonList ,
R.layout.list_item2, new String[]{"Name", "Physician_Key",
"Specialization","ProviderName","EmailId","Location"}, new
int[]{R.id.Name,
R.id.Physician_key,
R.id.Specialization,R.id.ProviderName,R.id.EmailId,R.id.Location});
listView.setAdapter(adapter);
listView1.setAdapter(adapter1);
Utility.setListViewHeightBasedOnChildren(listView);
Utility.setListViewHeightBasedOnChildren(listView1);
}
}
public class SendPostRequest extends AsyncTask<String, Void, String> {
protected void onPreExecute(){}
protected String doInBackground(String... arg0) {
try {
URL url = new URL("https://example.com");
URL url1 = new URL("https://xyz.sharedinfo"); // here is your URL path
final JSONObject postDataParams = new JSONObject();
final JSONObject postDataParams1=new JSONObject();
/* postDataParams.put("name", "abc");
postDataParams.put("email", "abc#gmail.com");*/ //here i have to post the data dynamically
postDataParams1.put("PhysicianKey","55") ;
postDataParams1.put("PatientKey", "5010");
postDataParams.put("Email","john#john.com");
runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(MainActivity.this, postDataParams.toString(), Toast.LENGTH_SHORT).show();
}
});
Log.e("params",postDataParams.toString());
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
HttpURLConnection conn1 = (HttpURLConnection) url1.openConnection();
conn.setReadTimeout(15000 /* milliseconds */);
conn.setConnectTimeout(15000 /* milliseconds */);
conn.setRequestMethod("POST");
conn.setDoInput(true);
conn.setDoOutput(true);
conn1.setReadTimeout(15000 /* milliseconds */);
conn1.setConnectTimeout(15000 /* milliseconds */);
conn1.setRequestMethod("POST");
conn1.setDoInput(true);
conn1.setDoOutput(true);
OutputStream os = conn.getOutputStream();
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(os, "UTF-8"));
writer.write(getPostDataString(postDataParams));
writer.flush();
writer.close();
os.close();
int responseCode=conn.getResponseCode()-1;
// if (responseCode == HttpsURLConnection.HTTP_OK) {
BufferedReader in=new BufferedReader(new InputStreamReader(conn.getInputStream()));
StringBuffer sb = new StringBuffer("");
String line="";
while((line = in.readLine()) != null) {
sb.append(line);
break;
}
in.close();
return sb.toString();
// }
/* else {
return new String("false : "+responseCode);
}*/
}
catch(Exception e){
return new String("Exception: " + e.getMessage());
}
}
#Override
protected void onPostExecute(String result) {
Toast.makeText(getApplicationContext(), result,
Toast.LENGTH_LONG).show();
}
}
public String getPostDataString(JSONObject params) throws Exception {
StringBuilder result = new StringBuilder();
boolean first = true;
Iterator<String> itr = params.keys();
while(itr.hasNext()){
String key= itr.next();
Object value = params.get(key);
if (first)
first = false;
else
result.append("&");
result.append(URLEncoder.encode(key,"UTF-8"));
result.append("=");
result.append(URLEncoder.encode(value.toString(),"UTF-8"));
}
return result.toString();
} }

you can use volley for handle http request
In android studio -put this line in your build.gradle
dependencies{
compile 'com.mcxiaoke.volley:library-aar:1.0.0'
}
Use this method (post) call this method
public void postData(){
StringRequest stringRequest = new StringRequest(Request.Method.POST, "YOUR URL",
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONObject jobject = new JSONObject(response);
Log.e("jobject ", jobject + "<return");
}catch (JSONException je){
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(getActivity(),error.toString(),Toast.LENGTH_LONG).show();
}
}){
#Override
protected Map<String,String> getParams(){
Map<String,String> params = new HashMap<String, String>();
params.put("Name","Mr.Lavanya");
params.put("Physician_Key", "Physician_Key");
params.put("ProviderName","ProviderName");
params.put("EmailId","EmailId");
params.put("Location","Location"),
Log.e("params",params+"");
return params;
}
};
RequestQueue requestQueue = Volley.newRequestQueue(getActivity());
requestQueue.add(stringRequest);
}

Related

Android use AsyncTask communication is not working

I'm trying to do Spring asynchronous communication.
I wrote the code, communication works, but both spring and android data values ​​are null.
why?
btn_login.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v) {
Intent intent = new Intent(getApplicationContext(), MainActivity.class);
String id=edit_email.getText().toString();
String password=edit_password.getText().toString();
ContentValues values=new ContentValues();
values.put("id",id);
values.put("password",password);
NetworkTask net=new NetworkTask("http://10.0.2.2:8080/Pet_Tuen_Tuen/login.do",values);
net.execute();
//new NetworkTask2().execute(values);
if(check==1) {
startActivity(intent);
}
}
public class NetworkTask extends AsyncTask<Void, Void, String> {
String url;
ContentValues values;
NetworkTask(String url, ContentValues values){
this.url = url;
this.values = values;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
//progress bar를 보여주는 등등의 행위
}
#Override
protected String doInBackground(Void... params) {
String result;
RequestHttpURLConnection requestHttpURLConnection = new RequestHttpURLConnection();
result = requestHttpURLConnection.request(url, values);
return result; // 결과가 여기에 담깁니다. 아래 onPostExecute()의 파라미터로 전달됩니다.
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
// 통신이 완료되면 호출됩니다.
// 결과에 따른 UI 수정 등은 여기서 합니다.
try {
check=1;
Log.println(Log.DEBUG, "------------------", result);
}catch (Exception e){
e.printStackTrace();
}
Toast.makeText(getApplicationContext(), result, Toast.LENGTH_LONG).show();
}
}
Request Connection code.
public class RequestHttpURLConnection {
public String request(String _url, ContentValues _params) {
HttpURLConnection urlConn = null;
// URL 뒤에 붙여서 보낼 파라미터.
StringBuffer sbParams = new StringBuffer();
/**
* 1. StringBuffer에 파라미터 연결
* */
// 보낼 데이터가 없으면 파라미터를 비운다.
if (_params == null)
sbParams.append("");
// 보낼 데이터가 있으면 파라미터를 채운다.
else {
// 파라미터가 2개 이상이면 파라미터 연결에 &가 필요하므로 스위칭할 변수 생성.
boolean isAnd = false;
// 파라미터 키와 값.
String key;
String value;
for (Map.Entry<String, Object> parameter : _params.valueSet()) {
key = parameter.getKey();
value = parameter.getValue().toString();
Log.println(Log.DEBUG,"=================>",value);
// 파라미터가 두개 이상일때, 파라미터 사이에 &를 붙인다.
if (isAnd)
sbParams.append("&");
sbParams.append(key).append("=").append(value);
// 파라미터가 2개 이상이면 isAnd를 true로 바꾸고 다음 루프부터 &를 붙인다.
if (!isAnd)
if (_params.size() >= 2)
isAnd = true;
}
}
/**
* 2. HttpURLConnection을 통해 web의 데이터를 가져온다.
* */
try {
URL url = new URL(_url);
urlConn = (HttpURLConnection) url.openConnection();
// [2-1]. urlConn 설정.
urlConn.setReadTimeout(10000);
urlConn.setConnectTimeout(15000);
urlConn.setRequestMethod("POST"); // URL 요청에 대한 메소드 설정 : GET/POST.
urlConn.setDoOutput(true);
urlConn.setDoInput(true);
urlConn.setRequestProperty("Accept-Charset", "utf-8"); // Accept-Charset 설정.
urlConn.setRequestProperty("Context_Type", "application/x-www-form-urlencoded");
// [2-2]. parameter 전달 및 데이터 읽어오기.
PrintWriter pw = new PrintWriter(new OutputStreamWriter(urlConn.getOutputStream()));
pw.write(sbParams.toString());
pw.flush(); // 출력 스트림을 flush. 버퍼링 된 모든 출력 바이트를 강제 실행.
pw.close(); // 출력 스트림을 닫고 모든 시스템 자원을 해제.
// [2-3]. 연결 요청 확인.
// 실패 시 null을 리턴하고 메서드를 종료.
if (urlConn.getResponseCode() != HttpURLConnection.HTTP_OK)
return null;
// [2-4]. 읽어온 결과물 리턴.
// 요청한 URL의 출력물을 BufferedReader로 받는다.
BufferedReader reader = new BufferedReader(new InputStreamReader(urlConn.getInputStream(), "UTF-8"));
// 출력물의 라인과 그 합에 대한 변수.
String line;
String page = "";
// 라인을 받아와 합친다.
while ((line = reader.readLine()) != null) {
page += line;
}
return page;
} catch (MalformedURLException e) { // for URL.
e.printStackTrace();
} catch (IOException e) { // for openConnection().
e.printStackTrace();
} finally {
if (urlConn != null)
urlConn.disconnect();
}
return null;
}
}
spring code
#Controller
public class MemberController {
#RequestMapping(value="/login.do",method=RequestMethod.POST)
public JSONObject login(HttpServletRequest request) {
System.out.println(request.getAttribute("id"));
System.out.println(request.getAttribute("password"));
JSONObject attr=new JSONObject();
attr.put("msg","ok");
return attr;
}
}
There is an error at run time.
But in spring data value is null.
Force sending data from spring to android but it is also null.
Why is the data not going over?
Communication is done by post.
Value needs to be URL encoded:
sbParams.append(key).append("=").append(URLEncoder.encode(value, "UTF-8"));
-------------------------------
urlConn.setReadTimeout(10000);
urlConn.setConnectTimeout(15000);
urlConn.setRequestMethod("POST");
urlConn.setDoOutput(true);
urlConn.setDoInput(true);
urlConn.setRequestProperty("Accept-Charset", "utf-8");.
urlConn.connect();
Still if not work then try
request.getParameter("id");

Getting Data from JSON?

I want to get the username from this
Json url.
I have this code but it doesn't let me get the data saying
Json parsing error
Here is the code:
HttpHandler.java
public class HttpHandler {
private static final String TAG = HttpHandler.class.getSimpleName();
public HttpHandler() {
}
public String makeServiceCall(String reqUrl) {
String response = null;
try {
URL url = new URL(reqUrl);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
// read the response
InputStream in = new BufferedInputStream(conn.getInputStream());
response = convertStreamToString(in);
} catch (MalformedURLException e) {
Log.e(TAG, "MalformedURLException: " + e.getMessage());
} catch (ProtocolException e) {
Log.e(TAG, "ProtocolException: " + e.getMessage());
} catch (IOException e) {
Log.e(TAG, "IOException: " + e.getMessage());
} catch (Exception e) {
Log.e(TAG, "Exception: " + 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');
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return sb.toString();
}
}
MainActivity.java
public class MainActivity extends AppCompatActivity {
private String TAG = MainActivity.class.getSimpleName();
private ProgressDialog pDialog;
private ListView lv;
// URL to get contacts JSON
private static String url = "https://someLink";
ArrayList<HashMap<String, String>> contactList;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
contactList = new ArrayList<>();
lv = (ListView) findViewById(R.id.list);
new GetContacts().execute();
}
/**
* Async task class to get json by making HTTP call
*/
private class GetContacts extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
// Showing progress dialog
pDialog = new ProgressDialog(MainActivity.this);
pDialog.setMessage("Please wait...");
pDialog.setCancelable(false);
pDialog.show();
}
#Override
protected Void doInBackground(Void... arg0) {
HttpHandler sh = new HttpHandler();
// Making a request to url and getting response
String jsonStr = sh.makeServiceCall(url);
Log.e(TAG, "Response from url: " + jsonStr);
if (jsonStr != null) {
try {
JSONObject jsonObj = new JSONObject(jsonStr);
// Getting JSON Array node
JSONArray contacts = jsonObj.getJSONArray("");
// looping through All Contacts
for (int i = 0; i < contacts.length(); i++) {
JSONObject c = contacts.getJSONObject(i);
String name = c.getString("username");
// tmp hash map for single contact
HashMap<String, String> contact = new HashMap<>();
// adding each child node to HashMap key => value
contact.put("username", name);
// adding contact to contact list
contactList.add(contact);
}
} 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(Void result) {
super.onPostExecute(result);
// Dismiss the progress dialog
if (pDialog.isShowing())
pDialog.dismiss();
/**
* Updating parsed JSON data into ListView
* */
ListAdapter adapter = new SimpleAdapter(
MainActivity.this, contactList,
R.layout.list_item, new String[]{"username"}, new int[]{R.id.name});
lv.setAdapter(adapter);
}
}
}
This is an example i found on google and tried to change it a bit in my needs.I've put an empty JsonArray.I also tried other examples but i can't understand what is going wrong.
**
> New question
If my url is like this?What is the difference with the other?
**
You don't have an array to parse in the output. Your URL giving you an Object. Your code should be something like this
if (jsonStr != null) {
try {
JSONObject jsonObj = new JSONObject(jsonStr);
String name = jsonObj.getString("username");
//... now use the whereever you want
}
catch (final JSONException e) {
//... put your error log
}
Please edit your code in MainActivity to get the username from json string as follows :
if(jsonStr!=null)
{
JSONObject jsonObj = new JSONObject(jsonStr);
if(jsonObj !=null)
{
String name = jsonObj .getString("username");
}
}
i suggest you to use this one.
public class HttpGetResources extends AsyncTask<String, Void, Object> {
#SuppressLint("StaticFieldLeak")
private ProgressBar progressBar;
private static final String RAW_DATE_FORMAT = "yyyy-MM-dd'T'HH:mm:ss.SSSz";
private String urlString;
private String apiName;
private Class Response_Class;
private static final Gson GSON = new GsonBuilder().setDateFormat(RAW_DATE_FORMAT).create();
private Context context;
public HttpGetResources(Context context,Class Response_Class, String apiName, String urlString) {
this.Response_Class = Response_Class;
this.apiName = apiName;
this.urlString = urlString;
this.context=context;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected void onPostExecute(Object response) {
super.onPostExecute(response);
}
HttpURLConnection conn = null;
OutputStreamWriter out = null;
Object result = null;
BufferedReader buffer = null;
final ExecutorService executor = Executors.newCachedThreadPool(Executors.defaultThreadFactory());
static public Future<Object> future;
#SuppressWarnings("unchecked")
#Override
protected Object doInBackground(final String... params) {
// JsonObject res=null;
future = executor.submit(new Callable<Object>() {
#Override
public Object call() throws IOException {
try {
URL url = new URL(urlString + apiName);
conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("POST");
conn.setRequestProperty("Content-Type", "application/json;charset=UTF-8");
conn.setConnectTimeout(3000);
conn.setReadTimeout(15000);
conn.setDoInput(true);
conn.setDoOutput(true);
out = new OutputStreamWriter(conn.getOutputStream());
out.write(params[0]);
out.flush();
out.close(); out=null;
buffer = new BufferedReader(new InputStreamReader(conn.getInputStream()));
// res= GSON.fromJson(buffer, JsonObject.class);
// result = new Gson().fromJson(res.toString(), Response_Class);
result = GSON.fromJson(buffer, Response_Class);
buffer.close(); buffer=null;
// result = new Gson().fromJson(res.toString(), Response_Class);
} catch (Exception e) {
//
} finally {
if (buffer!=null) {
try {
buffer.close();
} catch (Exception e) { //
}
}
if (out != null) {
try {
out.close();
} catch (Exception e) { //
}
}
if (conn != null) {
conn.disconnect();
}
}
return result;
}
});
try {
result = future.get(10, TimeUnit.SECONDS);
} catch (Exception ignored) {
}
return result;
}
}
--and call method--
public synchronized Object HttpGetRes(final Object REQUEST_CLASS, final Class RESPONSE_CLASS, final String
API_NAME, final String URL) {
if(isNetworkAvailable()) {
response = null;
try {
Log.e(API_NAME, "url: " + URL);
Log.e(REQUEST_CLASS.getClass().getSimpleName(), new Gson().toJson(REQUEST_CLASS));
HttpGetResources resource = new HttpGetResources(BaseContext,RESPONSE_CLASS, API_NAME,
URL);
response = resource.execute(new Gson().toJson(REQUEST_CLASS)).get();
} catch (InterruptedException | ExecutionException e) {
e.printStackTrace();
}
if (response != null) {
String x = new Gson().toJson(response);
Log.e(RESPONSE_CLASS.getSimpleName(), x);
return response;
} else {
}
}
return null;
}
Try to use GSON library in the future, it will auto convert the JSON object to a java object automatically for you. This will be useful to avoid parsing complex JSON objects or JSON arrays. https://github.com/google/gson

JSON Parsing error: No value for JSON array [duplicate]

This question already has answers here:
how to parse JSONArray in android
(3 answers)
Closed 4 years ago.
I have a code where i should pass an static user id for authentication and then fetch the JSON response from the URL and display it in listview. But i get an error that says "JSON Parsing error: No value in (JSON array)". Please help
MainActivity.java:
public class MainActivity extends AppCompatActivity {
private String TAG = MainActivity.class.getSimpleName();
private ProgressDialog pDialog;
private ListView lv;
// URL to get contacts JSON
private static String url = "url";
ArrayList<HashMap<String, String>> contactList;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
contactList = new ArrayList<>();
lv = (ListView) findViewById(R.id.list);
new GetContacts().execute();
}
/**
* Async task class to get json by making HTTP call
*/
private class GetContacts extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
// Showing progress dialog
pDialog = new ProgressDialog(MainActivity.this);
pDialog.setMessage("Please wait...");
pDialog.setCancelable(false);
pDialog.show();
}
#Override
protected Void doInBackground(Void... arg0) {
List<NameValuePair> list=new ArrayList<>();
list.add(new BasicNameValuePair("user_id", "2"));
HttpHandler sh = new HttpHandler();
// Making a request to url and getting response
String jsonStr = sh.makeServiceCall(url);
Log.e(TAG, "Response from url: " + jsonStr);
if (jsonStr != null) {
try {
JSONObject jsonObj = new JSONObject(jsonStr);
// Getting JSON Array node
JSONArray contacts = jsonObj.getJSONArray("promotion_lists");
// looping through All Contacts
for (int i = 0; i < contacts.length(); i++) {
JSONObject c = contacts.getJSONObject(i);
String promotion_id = c.getString("promotion_id");
String promotion_title = c.getString("promotion_title");
String promotion_description = c.getString("promotion_description");
//
HashMap<String, String> contact = new HashMap<>();
// adding each child node to HashMap key => value
contact.put("promotion_id", promotion_id);
contact.put("promotion_title", promotion_title);
contact.put("promotion_description", promotion_description);
// adding contact to contact list
contactList.add(contact);
}
} 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(Void result) {
super.onPostExecute(result);
Log.e("SignUpRsp", String.valueOf(result));
// Dismiss the progress dialog
if (pDialog.isShowing())
pDialog.dismiss();
/**
* Updating parsed JSON data into ListView
* */
ListAdapter adapter = new SimpleAdapter(
MainActivity.this, contactList,
R.layout.list_item, new String[]{"promotion_id", "promotion_title",
"promotion_description"}, new int[]{R.id.promotion_id,
R.id.promotion_title, R.id.promotion_desc});
lv.setAdapter(adapter);
}
}
public String PostData(String[] valuse) {
String s="";
try
{
HttpClient httpClient=new DefaultHttpClient();
HttpPost httpPost=new HttpPost("url");
List<NameValuePair> list=new ArrayList<>();
list.add(new BasicNameValuePair("user_id", "value"));
httpPost.setEntity(new UrlEncodedFormEntity(list));
HttpResponse httpResponse= httpClient.execute(httpPost);
HttpEntity httpEntity=httpResponse.getEntity();
s= readResponse(httpResponse);
}
catch(Exception exception) {}
return s;
}
public String readResponse(HttpResponse res) {
InputStream is=null;
String return_text="";
try {
is=res.getEntity().getContent();
BufferedReader bufferedReader=new BufferedReader(new InputStreamReader(is));
String line="";
StringBuffer sb=new StringBuffer();
while ((line=bufferedReader.readLine())!=null)
{
sb.append(line);
}
return_text=sb.toString();
} catch (Exception e)
{
}
return return_text;
}
}
JSON Response:
{
"status": "1",
"message": "Ok",
"promotion_lists": [
{
"promotion_id": "3",
"promotion_image_name": "1.jpg",
"promotion_image_url": "url.jpg",
"promotion_title": "winner",
"promotion_description": "good\ngold\nred",
"admin_status": "1",
"promotion_status": "1",
"promotion_status_description": "Live"
},
]
}
Your JSON parsing is correct
You need to parse your JSON if your response status response code is 1
SAMPLE CODE
Try this
if (jsonStr != null) {
try {
JSONObject jsonObj = new JSONObject(jsonStr);
// check here of your status of response
// is status is 0 USER NOT FOUND
if(jsonObj.getString("status").equals("0")){
MainActivity.this.runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(MainActivity.this, jsonObj.getString("message"), Toast.LENGTH_SHORT).show();
}
});
// is status is 1 PARSE YOUR JSON
}else {
JSONArray contacts = jsonObj.getJSONArray("promotion_lists");
// looping through All Contacts
for (int i = 0; i < contacts.length(); i++) {
JSONObject c = contacts.getJSONObject(i);
String promotion_id = c.getString("promotion_id");
String promotion_title = c.getString("promotion_title");
String promotion_description = c.getString("promotion_description");
HashMap<String, String> contact = new HashMap<>();
// adding each child node to HashMap key => value
contact.put("promotion_id", promotion_id);
contact.put("promotion_title", promotion_title);
contact.put("promotion_description", promotion_description);
// adding contact to contact list
contactList.add(contact);
}
}
} 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();
}
});
}
}
Your json also has an issue, can you try with this output json. Last comma(,) in an array is not required.
{
"status": "1",
"message": "Ok",
"promotion_lists": [
{
"promotion_id": "3",
"promotion_image_name": "1.jpg",
"promotion_image_url": "url.jpg",
"promotion_title": "winner",
"promotion_description": "good\ngold\nred",
"admin_status": "1",
"promotion_status": "1",
"promotion_status_description": "Live"
}
]
}
JSONArray throw error because promotion_lists with a item but has needless comma.
{
"status": "1",
"message": "Ok",
"promotion_lists": [
{
"promotion_id": "3",
"promotion_image_name": "1.jpg",
"promotion_image_url": "url.jpg",
"promotion_title": "winner",
"promotion_description": "good\ngold\nred",
"admin_status": "1",
"promotion_status": "1",
"promotion_status_description": "Live"
}
]
}
Your JSON parse looks fine. The issue is with the your JSON response. It is not a valid JSON Response as there is a unnecessary comma after the JSON Array "promotion_lists". Try removing the comma.
You can use this solution
public class GetContacts extends AsyncTask<String, Void, String> {
protected void onPreExecute() {
pDialog = new ProgressDialog(MainActivity.this);
pDialog.setMessage("Please wait...");
pDialog.setCancelable(false);
pDialog.show();
}
protected String doInBackground(String... arg0) {
try {
URL url = new URL(URL HERE);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("POST");
conn.setRequestProperty("Content-Type", "application/json;charset=UTF-8");
conn.setRequestProperty("Accept", "application/json");
conn.setDoOutput(true);
conn.setDoInput(true);
conn.setReadTimeout(5000);
conn.setConnectTimeout(5000);
JSONObject postDataParams = new JSONObject();
postDataParams.put("user_id", user_id);
Log.i("JSON", postDataParams.toString());
DataOutputStream os = new DataOutputStream(conn.getOutputStream());
//os.writeBytes(URLEncoder.encode(jsonParam.toString(), "UTF-8"));
os.writeBytes(postDataParams.toString());
os.flush();
os.close();
Log.i("STATUS", String.valueOf(conn.getResponseCode()));
Log.i("MSG", conn.getResponseMessage());
int responseCode = conn.getResponseCode();
if (responseCode == HttpsURLConnection.HTTP_OK) {
BufferedReader in = new BufferedReader(new
InputStreamReader(
conn.getInputStream()));
StringBuffer sb = new StringBuffer("");
String line = "";
while ((line = in.readLine()) != null) {
sb.append(line);
break;
}
in.close();
conn.disconnect();
return sb.toString();
} else {
conn.disconnect();
return new String("false : " + responseCode);
}
} catch (Exception e) {
return new String("Exception: " + e.getMessage());
}
}
#Override
protected void onPostExecute(String jsonStr) {
try {
pDialog();
Log.e(TAG, "Response from url: " + jsonStr);
if (jsonStr != null) {
try {
JSONObject jsonObj = new JSONObject(jsonStr);
// Getting JSON Array node
JSONArray contacts = jsonObj.getJSONArray("promotion_lists");
// looping through All Contacts
for (int i = 0; i < contacts.length(); i++) {
JSONObject c = contacts.getJSONObject(i);
String promotion_id = c.getString("promotion_id");
String promotion_title = c.getString("promotion_title");
String promotion_description = c.getString("promotion_description");
//
HashMap<String, String> contact = new HashMap<>();
// adding each child node to HashMap key => value
contact.put("promotion_id", promotion_id);
contact.put("promotion_title", promotion_title);
contact.put("promotion_description", promotion_description);
// adding contact to contact list
contactList.add(contact);
}
/**
* Updating parsed JSON data into ListView
* */
ListAdapter adapter = new SimpleAdapter(
MainActivity.this, contactList,
R.layout.list_item, new String[]{"promotion_id", "promotion_title",
"promotion_description"}, new int[]{R.id.promotion_id,
R.id.promotion_title, R.id.promotion_desc});
lv.setAdapter(adapter);
} catch (final JSONException e) {
Log.e(TAG, "Json parsing error: " + e.getMessage());
Toast.makeText(getApplicationContext(),
"Json parsing error: " + e.getMessage(),
Toast.LENGTH_LONG)
.show();
}
} else {
Log.e(TAG, "Couldn't get json from server.");
Toast.makeText(getApplicationContext(),
"Json parsing error: " + e.getMessage(),
Toast.LENGTH_LONG)
.show();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}
One more thing you dont need to use runOnUiThread in Asynctask because
both are helper threads , which are used to Update UI,you dont have to
use runOnUIThread in it , just simple show toast without using it, it
will show it , read the documentation
https://developer.android.com/guide/components/processes-and-threads

Parse json multiple url

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

AsyncTask with timeout

I want my application throws timeout after 10 seconds in AsyncTask.So what should i do ? If i am not using this so my application is crash.
And sorry for my bad English.
this is my AsyncTask
LoginTask
public class LoginTask extends AsyncTask<Void, Integer, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
progress.setVisibility(View.VISIBLE);
}
#Override
protected Void doInBackground(Void... params) {
/* JSONParser jParser = new JSONParser();
// JSONArray data = null;
String jsonstr = jParser.makeServiceCall(URL, JSONParser.POST);*/
BufferingH call = new BufferingH();
jsonstr = call.makeBufferCall(URL);
System.out.println("Json url view string " + jsonstr);
return null;
}
#SuppressLint("ShowToast")
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
if (jsonstr != null) {
try {
JSONObject jobj = new JSONObject(jsonstr);
URLmessage = jobj.getString("message").toString();
JSONArray jarray = jobj.getJSONArray("Data");
for (int i = 0; i < jarray.length(); i++) {
JSONObject jobjj = jarray.getJSONObject(i);
Username = jobjj.getString("r_name");
Password = jobjj.getString("r_password");
FirstName=jobjj.getString("first_name");
}
} catch (Exception e) {
e.printStackTrace();
}
} else {
Toast.makeText(getApplicationContext(), "Invalid username password", Toast.LENGTH_SHORT).show();
Log.e("Login Screen", "Couldn't get any data from the url");
}
try {
if (URLmessage.matches("Invalid Login")) {
Toast.makeText(getApplicationContext(), "Invalid Login.....",
Toast.LENGTH_SHORT).show();
// Intent intent = new Intent(Login.this, Register.class);
// startActivity(intent);
} else {
Toast.makeText(getApplicationContext(), "Login Successful...",
Toast.LENGTH_SHORT).show();
Password = et_password.getText().toString();
Username = et_username.getText().toString();
Intent k = new Intent(getBaseContext().getApplicationContext(),
MainActivity.class);
k.putExtra("regId", regId);
startActivity(k);
finish();
SettingsFragment.setDefaults("Username", Username, getApplicationContext());
SettingsFragment.setDefaults("Password", Password, getApplicationContext());
SettingsFragment.setDefaults("FirstName", Login.FirstName, getApplicationContext());
Toast.makeText(getApplicationContext(), "FirstName = "+FirstName, Toast.LENGTH_SHORT).show();
// gcmregister_from_sharedpref
gcmafterregistration();
overridePendingTransition(R.anim.left_to_right, R.anim.right_to_left);
}
} catch (Exception e) {
e.printStackTrace();
}
progress.setVisibility(View.INVISIBLE);
}
}
And this is my logcat so you can batter understand.
I have put one dummy code change your code by referring this.
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
if (commonUtils.isNetworkAvailable(mContext)) {
NewHistoryAsync task = new NewHistoryAsync(getContext(), listDataHeader, listDataChild);
task.execute(CommonUtils._History + "ID=" + userUhid);
} else {
Toast.makeText(mContext, "No Network Available!!",
Toast.LENGTH_LONG).show();
}
private class NewHistoryAsync extends AsyncTask<String, String, String> {
ProgressDialog progressDialog;
Context mContext;
List listDataHeader;
HashMap listDataChild;
public NewHistoryAsync(Context context, List listDataHeaderList, HashMap listDataChildMap) {
mContext = context;
listDataHeader = listDataHeaderList;
listDataChild = listDataChildMap;
this.listDataHeader = new ArrayList<String>();
this.listDataChild = new HashMap<String, List<String>>();
}
#Override
protected void onPreExecute() {
super.onPreExecute();
progressDialog = new ProgressDialog(getActivity());
progressDialog = ProgressDialog.show(mContext, Html.fromHtml(
"<b>Heading<b>"), Html.fromHtml("<medium>Downloading Details..</medium>"), true);
// progressDialog.setTitle("Downloading Details");
progressDialog.setCancelable(false);
progressDialog.setCanceledOnTouchOutside(false);
progressDialog.show();
}
#Override
protected String doInBackground(String... params) {
String resResult = NewHistoryService(params[0]);
JSONObject jsonResponse;
try {
//JSONObject jsonObject = new JSONObject(resResult);
JSONArray jsonArray = new JSONArray(resResult);
// Log.i("doinb---> ", resResult);
/* ArrayList<ClaimsHistoryNewSearchModel> listDataHeader=new ArrayList<ClaimsHistoryNewSearchModel>();*/
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObject = jsonArray.getJSONObject(i);
List<String> historyResult = new ArrayList<String>();
historyResult.add((jsonObject.get("AdmissionDate").toString()));
historyResult.add((jsonObject.get("DischargeDate").toString()));
//AdmissionDate= exact name to ur json response from server
listDataHeader.add(KeyString);
listDataChild.put(KeyString, historyResult);
}
} catch (Exception e) {
e.printStackTrace();
}
return resResult;
}
#Override
protected void onProgressUpdate(String... values) {
Toast.makeText(mContext, values[0], Toast.LENGTH_SHORT).show();
}
#Override
protected void onPostExecute(String result) {
if (progressDialog != null && progressDialog.isShowing() == true) {
progressDialog.dismiss();
if (result.equals("[]")) {
Toast.makeText(mContext, "No Details found!!",
Toast.LENGTH_LONG).show();
} else
// Log.i("Result:", result);
// Log.i("listDataHeader:", listDataHeader.toString());
// Log.i("listDataChild:", listDataChild.toString());
listAdapter = new ClaimHistoryNewAdapter(getActivity(), listDataHeader, listDataChild);
if (listDataHeader != null && listDataHeader.size() > 0 && listDataChild != null && listDataHeader.size() > 0) {
expListView.setAdapter(listAdapter);
} else {
// setting list adapter
tClaimHistory.setVisibility(View.VISIBLE);
}
}
}
public String NewHistoryService(String serviceUrl) {
StringBuffer response = new StringBuffer();
URL url = null;
HttpURLConnection conn = null;
try {
url = new URL(serviceUrl);
conn = (HttpURLConnection) url.openConnection();
conn.setConnectTimeout(30000);
conn.setDoOutput(false);
conn.setUseCaches(false);
conn.setRequestMethod("GET");
conn.setRequestProperty("Content-Type",
"application/x-www-form-urlencoded;charset=UTF-8");
int status = conn.getResponseCode();
if (status != 200) {
throw new IOException("Post failed with error code " + status);
}
// Get Response
InputStream is = conn.getInputStream();
BufferedReader rd = new BufferedReader(new InputStreamReader(is));
String line;
while ((line = rd.readLine()) != null) {
response.append(line);
}
rd.close();
} catch (Exception e) {
e.printStackTrace();
//ErrorLogger.writeLog(claimNo, "Error Msg : "+e.getMessage()+"..."+ErrorLogger.StackTraceToString(e), "sendSyncService Failed");
//response.append("Error");
}
Log.v("Response:", response.toString());
return response.toString();
}
}
}
Use this JsonParser class
Hope it will help you
import android.util.Log;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
public class JSONParser {
public JSONParser() {
}
public String makeServiceCall(String serviceUrl) {
Boolean registered = false;
StringBuffer response = new StringBuffer();
URL url = null;
HttpURLConnection conn = null;
try {
url = new URL(serviceUrl);
conn = (HttpURLConnection) url.openConnection();
conn.setConnectTimeout(30000);
conn.setDoOutput(false);
conn.setUseCaches(false);
conn.setRequestMethod("GET");
conn.setRequestProperty("Content-Type",
"application/x-www-form-urlencoded;charset=UTF-8");
int status = conn.getResponseCode();
if (status != 200) {
throw new IOException("Post failed with error code " + status);
}
registered = true;
// Get Response
InputStream is = conn.getInputStream();
BufferedReader rd = new BufferedReader(new InputStreamReader(is));
String line;
while ((line = rd.readLine()) != null) {
response.append(line);
}
rd.close();
} catch (Exception e) {
e.printStackTrace();
/* ErrorLogger.writeLog(claimNo, "Error Msg : "+e.getMessage()+"..."+ErrorLogger.StackTraceToString(e), "sendSyncService Failed");
response.append("Error");*/
}
Log.v("Response:", response.toString());
return response.toString();
}
}
setConnectionTimeout(Your Time);

Categories

Resources