I'm trying to get this array of images in this json bellow and display it in GridView but i don't know why i can't reach that >>>
{
id: 241,
title: "title",
image: "1469370455.jpg",
description: " descriotion ",
images: [
"1469370455.jpg",
"1469370458.jpg",
"1469370481.jpg",
"1469370484.jpg"
]}
and this is my full AyncTask.
private class AysncImages extends AsyncTask<String, Void, Integer> {
#Override
protected void onPreExecute() {
super.onPreExecute();
// Showing progress dialog
// pDialog = new ProgressDialog(getActivity());
// pDialog.setMessage("Please wait...");
// pDialog.setCancelable(false);
// pDialog.show();
}
#Override
protected Integer doInBackground(String... arg0) {
// Building Parameters
HttpHandler sh = new HttpHandler();
String jsonStr = sh.makeServiceCall(String.valueOf(Config.BASE_URL));
//jsonStr = sh.makeServiceCall(url + 373); //or url + ID
Log.i(TAG, "doInBackground Image: " + jsonStr);
if (jsonStr != null) {
try {
JSONObject jsonObj = new JSONObject(jsonStr);
JSONArray arrayObj = jsonObj.getJSONArray("images");
Log.i(TAG, "array: "+ jsonObj);
GridItem item = new GridItem();
for (int i = 0; i < arrayObj.length(); i++) {
String images = arrayObj.getString(i);
Log.i(TAG, "parseResult: " + jsonObj);
item.setImage(IMAGE_LINK + images);//IMAGE_LINK +
Log.i(TAG, "parseResult: " + IMAGE_LINK + " " + images);
mGridData.add(item);
}
// Getting JSON Array node
} catch (JSONException e1) {
e1.printStackTrace();
}
}
return null;
}
#Override
protected void onPostExecute(Integer result) {
// if (result == 1) {
mGridAdapter.setGridData(mGridData);
//} else {
// Toast.makeText(getActivity(), "Failed to fetch data!", Toast.LENGTH_SHORT).show();
// }
//Hide progressbar
mProgressBar.setVisibility(View.GONE);
}
}
In my log i can't reach jsonObj or arrayObj I just can reach jsonStr what I'm missing ?
My Log for jsonStr
the json string you get is [{id:abc,...}]
but a JsonObject should start with {id:abc,...}
maybe you try to remove the '[' and ']' at the end of string in order to get the object
as start with '[' should be an array
Related
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
i'm trying to parse this json
{
"data": [
{ "name": "4th Floor",
"is_broken": true,
"is_repaired": false,
"is_ok": false,
"asset_parent": {
"name": "Buni Building",
"is_broken": true,
"is_repaired": false,
"is_ok": false
}
}
]
}
with this code
class daftarAset extends AsyncTask<String, String, String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(getActivity());
pDialog.setMessage("Sedang menampilkan...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
#Override
protected String doInBackground(String... params) {
String link_url = "https://example.com/api/assets";
HttpHandler sh = new HttpHandler();
String json = sh.makeServiceCall(link_url);
Log.e(TAG, "Response from url: " + json);
if (json != null) {
try {
JSONObject jsonObject = new JSONObject();
JSONArray data = jsonObject.getJSONArray("data");
for (int i = 0; i < data.length(); i++) {
JSONObject ar = data.getJSONObject(i);
String aset = ar.getString("name");
JSONObject parent = ar.getJSONObject("asset_parent");
String nama = parent.getString("name");
HashMap map = new HashMap();
map.put(in_aset, aset);
map.put(in_ruang, nama);
data_map.add(map);
}
} catch (final JSONException e) {
Log.e(TAG, "Json parsing error: " + e.getMessage());
getActivity().runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(getActivity().getApplicationContext(),
"Json parsing error: " + e.getMessage(),
Toast.LENGTH_LONG).show();
}
});
}
getActivity().runOnUiThread(new Runnable() {
#Override
public void run() {
list = (ListView) getView().findViewById(R.id.baik_list);
adapter = new AssetsAdapter(getActivity(), data_map);
list.setAdapter(adapter);
setListViewHeightBasedOnChildren(list);
}
});
}
return null;
}
#Override
protected void onPostExecute(String s) {
pDialog.dismiss();
}
and it says error that no value for data. i dont know why the data said no value where i already call it before with JSONArray. it must be nothing to do with the listview where i have to put the value.
please help why it says has no value for data but it actualy has
You're getting error because you aren't passing the json string to your json object.
it should be
JSONObject jsonObject = new JSONObject(json);
instead of
JSONObject jsonObject = new JSONObject(); //json is missing here
I have this method to get data from server using volley and store it into sqlite database using ormlite. I'm doing this on splash screen. so now I want to show some progressbar when this process happen, the progress bar already appear and now I want to set the progress of progress bar inside the for loop. But I dont know why my progress bar keep on 0% until the process finish. when I look at the log the progress keep update but maybe because it inside a loop the progress not appear. How can I make the progress appear in my progressdialog?? below is my code
private void fetchMOffice() {
mOfficeAdapter = new TableMOfficeAdapter(this);
List<TableMOffice> listOffice = mOfficeAdapter.getAllDatabyLup();
progressBar = new ProgressDialog(SplashScreenActivity.this);
progressBar.setCancelable(true);
progressBar.setMessage("Downloading File...");
progressBar.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
progressBar.setProgress(0);
progressBar.setMax(100);
showDialog();
for (int i=0; i<listOffice.size(); i++) {
TableMOffice item = listOffice.get(i);
lupMOffice = item.getLup();
// locationIdArray.add(item.getKode_office());
break;
}
Log.e(TAG, "lup fetchMOffice: " +lupMOffice );
StringRequest strReq = new StringRequest(Request.Method.POST,
ConnectionManager.MASTER_M_OFFICE, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.e(TAG, "response: " + response);
try {
JSONObject obj = new JSONObject(response);
dbAdapter = new TableMOfficeAdapter(SplashScreenActivity.this);
// dbAdapter.deleteAll();
// SQLiteStatement insert = mDb.compileStatement(sql);
// check for error flag
if (obj.getBoolean("error") == false) {
jsonArray = obj.getJSONArray("m_office");
for ( i = 0; i < jsonArray.length(); i++) {
JSONObject versionObj = null;
versionObj = (JSONObject) jsonArray.get(i);
int id = versionObj.getInt("id");
String office = versionObj.getString("office");
String kode_office = versionObj.getString("kode_office");
String channel = versionObj.getString("channel");
String jenis = versionObj.getString("jenis");
String alamat = versionObj.getString("alamat");
String kota = versionObj.getString("kota");
String propinsi = versionObj.getString("propinsi");
String pic = versionObj.getString("pic");
String pic_phone = versionObj.getString("pic_phone");
String map_lat = versionObj.getString("map_lat");
String map_lng = versionObj.getString("map_lng");
String upd = versionObj.getString("upd");
String lup = versionObj.getString("lup");
String ket = versionObj.getString("ket");
String region = versionObj.getString("region");
String rek = versionObj.getString("rek");
String bank = versionObj.getString("bank");
String rental = versionObj.getString("rental");
Log.e("isitabeloffice", Integer.toString(id));
ctx = getApplicationContext();
dbAdapter.delete(SplashScreenActivity.this,id);
//dbAdapter.delete(ctx,id);
dbAdapter.insertData(new TableMOffice(), id, office, kode_office, channel,
jenis, alamat, kota, propinsi, pic, pic_phone, map_lat, map_lng,
upd, lup, ket, region, rek, bank, rental);
progress = (i+1)*100/jsonArray.length();
progressBar.setProgress(progress);
}
} else {
}
} catch (Exception e) {
Log.e(TAG, "json parsing error: " + e.getMessage());
//Toast.makeText(SplashScreenActivity.this, "Json parse error: " + e.getMessage(), Toast.LENGTH_LONG).show();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
NetworkResponse networkResponse = error.networkResponse;
Log.e(TAG, "Volley error: " + error.getMessage() + ", code: " + networkResponse);
hideDialog();
//Toast.makeText(SplashScreenActivity.this, "Volley error: " + error.getMessage(), Toast.LENGTH_SHORT).show();
}
})
{
#Override
protected Map<String, String> getParams() {
Map<String, String> params = new HashMap<>();
Log.e(TAG, "params: " + params.toString());
return params;
}
};
MyApplication.getInstance().addToRequestQueue(strReq);
}
I want to get an url from this link:
"http://graph.facebook.com/10202459285618351/picture?type=large&redirect=false"
it gives result:
{
"data": {
"url": "https://fbcdn-profile-a.akamaihd.net/hprofile-ak-xap1/t1.0- 1/s200x200/10342822_10202261537234765_3194866551853134720_n.jpg",
"is_silhouette": false
}
}
I tried,
private class GetContacts extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
// Showing progress dialog
pDialog = new ProgressDialog(AccountActivity.this);
pDialog.setMessage("Please wait...");
pDialog.setCancelable(false);
pDialog.show();
}
#Override
protected Void doInBackground(Void... arg0) {
// Creating service handler class instance
ServiceHandler sh = new ServiceHandler();
String jsonStr = sh.makeServiceCall(fbPicURL, ServiceHandler.GET);
Log.d("Response: ", "> " + jsonStr);
if (jsonStr != null) {
try {
JSONObject jsonObj = new JSONObject(jsonStr);
// Getting JSON Array node
fbRealURL = jsonObj.getString("url");
// Phone node is JSON Object
Toast.makeText(AccountActivity.this, fbRealURL,
Toast.LENGTH_LONG).show();
// tmp hashmap for single contact
}
catch (JSONException e) {
e.printStackTrace();
}
} else {
Log.e("ServiceHandler", "Couldn't get any data from the url");
}
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
* */
Toast.makeText(AccountActivity.this, fbRealURL,
Toast.LENGTH_LONG).show();
}
}
But returning null and its not crashing..
You have to get the data object first like this:
try {
JSONObject jsonObj = new JSONObject(jsonStr);
fbRealURLObj = jsonObj.getJSONObject("data");
fbRealURL = fbRealURLObj.getString("url");
// Phone node is JSON Object
Toast.makeText(AccountActivity.this, fbRealURL,
Toast.LENGTH_LONG).show();
// tmp hashmap for single contact
}
I have made a ListView and made a custom adapter for it,I am calling two Asynctask one for getting all messages from webservice and another is for reply of the message,I want to append the replied message to the ListView. Currently i am not getting it right way. My code is as below:
main.java
import com.epe.yehki.adapter.ChatAdapter;
import com.epe.yehki.backend.BackendAPIService;
import com.epe.yehki.uc.Header;
import com.epe.yehki.uc.Menu;
import com.epe.yehki.util.Const;
import com.epe.yehki.util.Pref;
import com.epe.yehki.util.Utils;
import com.example.yehki.R;
public class ChatHistoryActivity extends Activity {
private ProgressDialog pDialog;
JSONArray msgArry;
JSONObject jsonObj;
private ChatAdapter chatContent;
ArrayList<HashMap<String, String>> msgList;
ListView lv;
JSONArray msgs = null;
String pro_id, pro_name, pro_img, grup_id, sender_id, cust_id;
TextView tv_switch;
public boolean flag = false;
Header header;
Menu menu;
Intent in;
Button reply;
RelativeLayout rl_reply;
EditText et_reply;
String url;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.activity_chat_history);
lv = (ListView) findViewById(R.id.list);
tv_switch = (TextView) findViewById(R.id.tv_switch);
header = (Header) findViewById(R.id.header_msg);
menu = (Menu) findViewById(R.id.menu_msg);
reply = (Button) findViewById(R.id.btn_reply);
rl_reply = (RelativeLayout) findViewById(R.id.rl_reply);
rl_reply.setVisibility(View.GONE);
et_reply = (EditText) findViewById(R.id.et_reply);
menu.setSelectedTab(3);
header.title.setText("Conversation");
msgList = new ArrayList<HashMap<String, String>>();
pro_id = getIntent().getStringExtra(Const.TAG_PRODUCT_ID);
sender_id = getIntent().getStringExtra(Const.TAG_CUSTOMER_ID);
grup_id = getIntent().getStringExtra(Const.TAG_GROUP_ID);
cust_id = Pref.getValue(ChatHistoryActivity.this, Const.PREF_CUSTOMER_ID, "");
/* new GetChatHistory().execute(); */
lv.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
// getting values from selected ListItem
rl_reply.setVisibility(View.VISIBLE);
}
});
// message reply ...!!Chat api(conversation)
reply.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
new DoReply().execute();
// new GetChatHistory().execute();
}
});
}
#Override
protected void onResume() {
super.onResume();
new GetChatHistory().execute();
}
private class GetChatHistory extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(ChatHistoryActivity.this);
pDialog.setMessage("Please wait...");
pDialog.setCancelable(false);
pDialog.show();
}
#Override
protected Void doInBackground(Void... arg0) {
// Creating service handler class instance
BackendAPIService sh = new BackendAPIService();
String query = Const.API_CHAT_HISTORY;
url = "?customer_id=" + cust_id + "&group_id=" + grup_id + "&sender_id=" + sender_id + "&product_id=" + pro_id;
url = url.replace(" ", "%20");
url = query + url;
System.out.println(":::::::::::::My MESSGES URL::::::::::::::" + url);
// Making a request to url and getting response
String jsonStr = sh.makeServiceCall(url, BackendAPIService.GET);
Log.d("Response: ", "> " + jsonStr);
try {
if (jsonStr != null) {
msgArry = new JSONArray(jsonStr);
if (msgArry != null && msgArry.length() != 0) {
// looping through All Contacts
System.out.println(":::::::::::FLAG IN SUB:::::::::::" + msgArry.length());
for (int i = 0; i < msgArry.length(); i++) {
JSONObject c = msgArry.getJSONObject(i);
String custID = c.getString(Const.TAG_CUSTOMER_ID);
String custName = c.getString(Const.TAG_CUSTOMER_NAME);
String proID = c.getString(Const.TAG_PRODUCT_ID);
String email = c.getString(Const.TAG_CUSTOMER_EMAIL);
String photo = Const.API_HOST + "/" + c.getString(Const.TAG_PHOTO);
String msg_body = c.getString(Const.TAG_MESSAGE_BODY);
HashMap<String, String> message = new HashMap<String, String>();
message.put(Const.TAG_CUSTOMER_ID, custID);
message.put(Const.TAG_CUSTOMER_NAME, custName);
message.put(Const.TAG_PRODUCT_ID, proID);
message.put(Const.TAG_CUSTOMER_EMAIL, email);
message.put(Const.TAG_PHOTO, photo);
message.put(Const.TAG_MESSAGE_BODY, msg_body);
msgList.add(message);
}
} else {
runOnUiThread(new Runnable() {
#Override
public void run() {
Utils.showCustomeAlertValidation(ChatHistoryActivity.this, "No messgaes found", "yehki", "Ok");
msgList.clear();
}
});
}
} else {
Log.e("ServiceHandler", "Couldn't get any data from the url");
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
// Dismiss the progress dialog
if (pDialog != null)
pDialog.dismiss();
System.out.println("::::::::::::inside post:::::::::::");
chatContent = new ChatAdapter(ChatHistoryActivity.this, msgList);
chatContent.notifyDataSetChanged();
lv.setAdapter(chatContent);
}
}
/*
* GET CONVERSATION LIST.........REPLY
*/
private class DoReply extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(ChatHistoryActivity.this);
pDialog.setMessage("Please wait...");
pDialog.setCancelable(false);
pDialog.show();
}
#Override
protected Void doInBackground(Void... arg0) {
// Creating service handler class instance
BackendAPIService sh = new BackendAPIService();
String query = Const.API_MESSAGE_REPLY;
url = "?customer_id=" + cust_id + "&group_id=" + grup_id + "&receiver_id=" + sender_id + "&product_id=" + pro_id + "&message=" + et_reply.getText().toString().trim();
url = url.replace(" ", "%20");
url = query + url;
System.out.println(":::::::::::::My MESSGES URL::::::::::::::" + url);
System.out.println(":::::::::::::::get chat history called:::::::::::::;;");
// Making a request to url and getting response
String jsonStr = sh.makeServiceCall(url, BackendAPIService.GET);
Log.d("Response: ", "> " + jsonStr);
try {
if (jsonStr != null) {
jsonObj = new JSONObject(jsonStr);
if (jsonObj.getString("status").equals("sucess")) {
// et_reply.setText("");
runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(ChatHistoryActivity.this, "Message has been sent", Toast.LENGTH_SHORT).show();
}
});
} else {
// et_reply.setText("");
runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(ChatHistoryActivity.this, "Message has not been sent", Toast.LENGTH_SHORT).show();
}
});
}
} else {
Log.e("ServiceHandler", "Couldn't get any data from the url");
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
System.out.println("::::::::::::inside post:::::::::::");
// Dismiss the progress dialog
if (pDialog != null)
pDialog.dismiss();
chatContent = new ChatAdapter(ChatHistoryActivity.this, msgList);
chatContent.notifyDataSetChanged();
lv.setAdapter(chatContent);
new GetChatHistory().execute();
}
}
}