I want to insert some items into the database. In the main activity, I retrieve information from the user and pass it to the another class to do some parsing. My JSONObject keeps showing up as NULL.
I am sorry if I am not clear with the question . I've tried to explain it as much as possible.
Below is the code your inputs are welcome
public class MainActivity extends Activity {
/** THE FOLLOWING STRINGS WILL BE DISPLAYED IN LOGCAT */
final String TAG = "########-------MAIN ACTIVITY: LOGIN--------######";
final String URL = "http://46.51.193.32/timereport/ses/sessions";
UserHelper userAdapter;
UserHelper db;
EditText edit_password,edit_username,edit_company;
String regName;
int duration = Toast.LENGTH_LONG;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
db = new UserHelper(this);
userAdapter = new UserHelper(this);
edit_password = (EditText)findViewById(R.id.password);
edit_username = (EditText)findViewById(R.id.user_name);
edit_company = (EditText)findViewById(R.id.company_string);
Button login = (Button)findViewById(R.id.login_button);
login.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
JSONObject jsonobj = new JSONObject();
try{
JSONObject subJson = new JSONObject();
subJson.put("username", edit_username.getText().toString());
subJson.put("password", edit_password.getText().toString());
subJson.put("company", edit_company.getText().toString());
jsonobj.put("user", subJson);
}
catch(JSONException e) {
Log.i("","#####-----error at catch jsonexception-----#####");
}
HandleJSON.SendHttpPost(URL, jsonobj);
String regNameSplit[] = regName.split("-");
try{
userAdapter.openDatabase();
long id = db.insertIntoDatabase(edit_username.getText().toString(),edit_company.getText().toString(), edit_password.getText().toString(),regNameSplit[0], regNameSplit[2]);
Toast.makeText(getApplicationContext(), "You have successfully logged in as: " +"\n" +regNameSplit[0], duration).show();
Log.i(TAG, "Printing value of id which will be inserted only to remove warnings "+id);
userAdapter.closeDatabase();
}
catch(SQLiteException e){
e.printStackTrace();
}
}
});
}
}
This is the class to which I am sending the JSON object to be parsed
public class HandleJSON{
UserHelper userAdapter;
private static final String TAG = "&&----HTTPClient-----**";
public static String SendHttpPost (String URL, JSONObject jsonobj) {
String regName = "";
try{
Log.v("Json object request is ",jsonobj.toString());
DefaultHttpClient httpClientInstance = GetHttpClient.getHttpClientInstance();
HttpPost httpPostRequest = new HttpPost(URL);
Log.v(TAG,"The url is "+URL);
StringEntity se;
se = new StringEntity(jsonobj.toString());
httpPostRequest.setEntity(se);
httpPostRequest.setHeader("Accept", "application/json");
httpPostRequest.setHeader("Content-type", "application/json");
long t = System.currentTimeMillis();
HttpResponse response = (HttpResponse) httpClientInstance.execute(httpPostRequest);
Log.i(TAG, "HTTPRESPONSE RECIEVED" +(System.currentTimeMillis()-t) + "ms");
String resultString = convertStreamToString(response.getEntity().getContent());
Log.v(TAG , "The response is " +resultString);
JSONObject jsonObj = new JSONObject(resultString);
JSONObject sessionJson = jsonObj.getJSONObject("session");
String sessionId = sessionJson.getString("sessionid");
String name = sessionJson.getString("name");
Log.v(TAG,"The session ID is "+sessionId);
Log.v(TAG,"The name is "+name);
regName = name+"-"+sessionId+"-"+URL;
} catch (Exception e){
e.printStackTrace();
}
return regName;
}
private static String convertStreamToString(InputStream is) {
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
StringBuilder sb = new StringBuilder();
String line = null;
try{
while((line = reader.readLine()) !=null ){
sb.append(line + "\n");
}
}
catch (IOException e){
e.printStackTrace();
} finally{
try {
is.close();
} catch (IOException e){
e.printStackTrace();
}
}
return sb.toString();
}
}
I've just added some of the code that was missing at the MainActivity,
String regNameSplit[] = regName.split("-");
keeps showing up as null
Instead of your convertStreamToString() method try using system provided EntityUtils.toString(entity).
IMPORTANT: do not catch generic Exception, this hides unchecked (runtime) exceptions. You might be hiding the JSONException that happens in JSONObject constructor.
Update:
You are calling SendHttpPost and not assigning result to variable:
HandleJSON.SendHttpPost(URL, jsonobj);
should be:
regName = HandleJSON.SendHttpPost(URL, jsonobj);
I don't see anything wrong with this, could you tell me what is the use of regname ?
at your mainactivity just change the following:
regname = HandleJSON.SendHttpPost(URL, jsonobj);
Your not calling back regname to be assigned to name and sessionid that you are returning at the sendhttppost.
Related
So I have been trying to figure out a way to save the Access Token I get from my API. I can successfully get the JSON response from my API and store it in my result variable within my doInBackground.
However, for some reason it is not getting saved in SharedPreferences in my onPostExecute.
The result variable contains this JSON string {"access_token":"4Oq6o8oAGRf4oflu3hrbsy18qeIfG1","expires_in":36000,"token_type":"Bearer","scope":"read write","refresh_token":"iocSNJ2PTVbph2RnWmcf0Zv69PDKjw"}, which I received from my API.
I have an algorithm that is supposed to save only the access_token for now.
My code is below:
WSAdapter.java
public class WSAdapter {
static public class SendAPIRequests extends AsyncTask<String, String, String> {
// Add a pre-execute thing
SharedPreferences ShPreference;
SharedPreferences.Editor PrefEditor;
static String MyPREFERENCES = "API Authentication";
String accessToken = "Access Token";
private WeakReference<Context> mLoginReference;
// constructor
public SendAPIRequests(Context context){
mLoginReference = new WeakReference<>(context);
}
#Override
protected String doInBackground(String... params) {
Thread.currentThread().setPriority(Thread.MAX_PRIORITY);
Log.e("TAG", params[0]);
Log.e("TAG", params[1]);
//String data = "";
StringBuilder result = new StringBuilder();
HttpURLConnection httpURLConnection = null;
try {
// Sets up connection to the URL (params[0] from .execute in "login")
httpURLConnection = (HttpURLConnection) new URL(params[2]).openConnection();
// Sets the request method for the URL
httpURLConnection.setRequestMethod("POST");
httpURLConnection.setRequestProperty("Content-Type", "application/json;charset=UTF-8");
httpURLConnection.setRequestProperty("Accept","application/json");
// Tells the URL that I am sending a POST request body
httpURLConnection.setDoOutput(true);
// Tells the URL that I want to read the response data
httpURLConnection.setDoInput(true);
// JSON object for the REST API
JSONObject jsonParam = new JSONObject();
jsonParam.put("client_id", "mYIHBd321Et3sgn7DqB8urnyrMDwzDeIJxd8eCCE");
jsonParam.put("client_secret", "qkFYdlvikU4kfhSMBoLNsGleS2HNVHcPqaspCDR0Wdrdex5dHyiFHPXctedNjugnoTq8Ayx7D3v1C1pHeqyPh1BjRlBTQiJYSuH6pi9EVeuyjovxacauGVeGdsBOkHI3");
jsonParam.put("username", params[0]);
jsonParam.put("password", params[1]);
jsonParam.put("grant_type", "password");
Log.i("JSON", jsonParam.toString());
// To write primitive Java data types to an output stream in a portable way
DataOutputStream wr = new DataOutputStream(httpURLConnection.getOutputStream());
// Writes out a byte to the underlying output stream of the data posted from .execute function
wr.writeBytes(jsonParam.toString());
// Flushes the jsonParam to the output stream
wr.flush();
wr.close();
// // Representing the input stream
InputStream in = new BufferedInputStream(httpURLConnection.getInputStream());
BufferedReader reader = new BufferedReader(new InputStreamReader(in));
// reading the input stream / response from the url
String line;
while ((line = reader.readLine()) != null) {
result.append(line);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
// Disconnects socket after using
if (httpURLConnection != null) {
httpURLConnection.disconnect();
}
}
Log.e("TAG", result.toString());
return result.toString();
}
#Override
protected void onPostExecute(String result) {
//super.onPostExecute(result);
// expecting a response code fro my server upon receiving the POST data
Log.e("TAG", result);
// retrieves the context passed
Context context = mLoginReference.get();
ShPreference = context.getSharedPreferences(MyPREFERENCES, Context.MODE_PRIVATE);
// edits shared preferences for authentication and authorization
PrefEditor = ShPreference.edit();
// to save the Access Token from the API
try {
JSONObject pJObject = new JSONObject(result);
PrefEditor.putString(accessToken, pJObject.getString("access_token"));
PrefEditor.apply();
// algorithm for parsing the JSONArray from the Django REST API
/*for (int i = 0; i < pJObjArray.length(); i++) {
// puts the current iterated JSON object from the array to another temporary object
JSONObject pJObj_data = pJObjArray.getJSONObject(i);
PrefEditor.putString(accessToken, pJObj_data.getString("access_token"));
PrefEditor.apply();
}*/
} catch (JSONException e) {
//Toast.makeText(JSonActivity.this, e.toString(), Toast.LENGTH_LONG).show();
Log.d("Json","Exception = "+e.toString());
}
}
}
This code below includes the code that reads the SharedPreferences. Which should be in the doInBackground of this AsyncTask as I need to put the access_token to the header.
This is supposed to be in the same class.
public class SendPostsRequest extends AsyncTask<String, String, String> {
TextView postsSect;
// Add a pre-execute thing
HttpURLConnection urlConnection;
// gets the activity context
private WeakReference<Context> mPostReference;
// to be able to access activity resources
Activity activity;
SharedPreferences ShPreference;
SharedPreferences.Editor PrefEditor;
String accessToken = "Access Token";
// constructor
public SendPostsRequest(Context context, Activity activity){
mPostReference = new WeakReference<>(context);
this.activity = activity;
}
#Override
protected String doInBackground(String... params) {
StringBuilder result = new StringBuilder();
// retrieves the context passed
Context context = mPostReference.get();
ShPreference = context.getSharedPreferences(MyPREFERENCES, Context.MODE_PRIVATE);
String APIAuthentication = "Bearer " + ShPreference.getString(accessToken, "");
try {
// Sets up connection to the URL (params[0] from .execute in "login")
urlConnection = (HttpURLConnection) new URL(params[0]).openConnection();
urlConnection.setRequestMethod("GET");
urlConnection.setRequestProperty ("Authorization", APIAuthentication);
urlConnection.connect();
InputStream in = new BufferedInputStream(urlConnection.getInputStream());
BufferedReader reader = new BufferedReader(new InputStreamReader(in));
String line;
while ((line = reader.readLine()) != null) {
result.append(line);
}
}catch( Exception e) {
e.printStackTrace();
}
finally {
urlConnection.disconnect();
}
return result.toString();
}
#Override
protected void onPostExecute(String result) {
// expecting a response code fro my server upon receiving the POST data
Log.e("TAG", result);
// gets the JSON files stored in the posts details class from Posts Activity
Posts.PostsDetails postsHelper = new Posts().new PostsDetails();
// retrieves the context passed
Context context = mPostReference.get();
// For posts
try {
JSONArray pJObjArray = new JSONArray(result);
// algorithm for parsing the JSONArray from the Django REST API
for (int i = 0; i < pJObjArray.length(); i++) {
// puts the current iterated JSON object from the array to another temporary object
JSONObject pJObj_data = pJObjArray.getJSONObject(i);
// inputs necesarry elements to the ListPosts function
postsHelper.setPost(pJObj_data.getInt("id"), pJObj_data.getString("post_title"), pJObj_data.getString("post_content"));
}
} catch (JSONException e) {
//Toast.makeText(JSonActivity.this, e.toString(), Toast.LENGTH_LONG).show();
Log.d("Json","Exception = "+e.toString());
}
// checks if context is not null before updating posts page
if (context != null){
postsSect = (TextView) activity.findViewById(R.id.PostsSection);
int lastFrJSONArray = postsHelper.getPostID().size() - 1;
// outputs the id of the very first post, something to put to the textview
postsSect.setText("id: " + postsHelper.getPostID().get(lastFrJSONArray - 2) + "\n");
for (int i = lastFrJSONArray; i >= 0; i--)
{
// appending the titles and contents of the current post
postsSect.append("title: " + postsHelper.getPostTitle().get(i) + "\n");
postsSect.append("content: " + postsHelper.getPostContent().get(i) + "\n");
// if this is the last post, then don't need to append id for the next post.
if (i != 0) {
postsSect.append("id: " + postsHelper.getPostID().get(i) + "\n");
}
}
}
}
}
UPDATE:
I have edited my JSON parsing algorithm.
Instead of parsing my JSON object from result as an array, this code here now parses it as an object. The JSONarray algorithm should be commented out.
The response you get from your webservice is actually not a JSONArray, but just a simple JSONObject. Hence change this line:
JSONArray pJObjArray = new JSONArray(result);
to
JSONObject pJObjArray = new JSONObject(result);
If You are not getting token just follow this code. it may help you.
//member variable
SharedPreferences ShPreference;
SharedPreferences.Editor PrefEditor;
String ApiToken;
OnCreate(){
ShPreference = context.getSharedPreferences(MyPREFERENCES, Context.MODE_PRIVATE);
ApiToken = ShPreference.getString(accessToken, "");
// call wherever you want
new SendPostsRequest(ApiToken).execute()
}
public class SendPostsRequest extends AsyncTask<String, String, String> {
private String APIToken;
TextView postsSect;
// Add a pre-execute thing
HttpURLConnection urlConnection;
// gets the activity context
// constructor
public SendPostsRequest(String APIToken){
this.APIToken = APIToken;
}
#Override
protected String doInBackground(String... params) {
StringBuilder result = new StringBuilder();
// retrieves the context passed
Context context = mPostReference.get();
String APIAuthentication = APIToken; // or you can direct pass
try {
// Sets up connection to the URL (params[0] from .execute in "login")
urlConnection = (HttpURLConnection) new URL(params[0]).openConnection();
urlConnection.setRequestMethod("GET");
urlConnection.setRequestProperty ("Authorization", APIAuthentication);
urlConnection.connect();
InputStream in = new BufferedInputStream(urlConnection.getInputStream());
BufferedReader reader = new BufferedReader(new InputStreamReader(in));
String line;
while ((line = reader.readLine()) != null) {
result.append(line);
}
}catch( Exception e) {
e.printStackTrace();
}
finally {
urlConnection.disconnect();
}
return result.toString();
}
#Override
protected void onPostExecute(String result) {
// expecting a response code fro my server upon receiving the POST data
Log.e("TAG", result);
// gets the JSON files stored in the posts details class from Posts Activity
Posts.PostsDetails postsHelper = new Posts().new PostsDetails();
// retrieves the context passed
Context context = mPostReference.get();
// For posts
try {
JSONArray pJObjArray = new JSONArray(result);
// algorithm for parsing the JSONArray from the Django REST API
for (int i = 0; i < pJObjArray.length(); i++) {
// puts the current iterated JSON object from the array to another temporary object
JSONObject pJObj_data = pJObjArray.getJSONObject(i);
// inputs necesarry elements to the ListPosts function
postsHelper.setPost(pJObj_data.getInt("id"), pJObj_data.getString("post_title"), pJObj_data.getString("post_content"));
}
} catch (JSONException e) {
//Toast.makeText(JSonActivity.this, e.toString(), Toast.LENGTH_LONG).show();
Log.d("Json","Exception = "+e.toString());
}
// checks if context is not null before updating posts page
if (context != null){
postsSect = (TextView) activity.findViewById(R.id.PostsSection);
int lastFrJSONArray = postsHelper.getPostID().size() - 1;
// outputs the id of the very first post, something to put to the textview
postsSect.setText("id: " + postsHelper.getPostID().get(lastFrJSONArray - 2) + "\n");
for (int i = lastFrJSONArray; i >= 0; i--)
{
// appending the titles and contents of the current post
postsSect.append("title: " + postsHelper.getPostTitle().get(i) + "\n");
postsSect.append("content: " + postsHelper.getPostContent().get(i) + "\n");
// if this is the last post, then don't need to append id for the next post.
if (i != 0) {
postsSect.append("id: " + postsHelper.getPostID().get(i) + "\n");
}
}
}
}
}
My app makes a call to FourSquare API. The call happens in my getResponse() function, and that function gets called every time I do new Explore().execute();
Now, I am able to get a string from the API... But when I pass that string to displayResults() function, it becomes null (I have a code comment below to show exactly where). And because this string becomes null, I can not parse the JSON. What is causing this issue?
public TextView mBusinessName;
public TextView mCategorie;
public WebView mLocationView;
private class Explore extends AsyncTask<Void, String, String>{
String resp = "";
#Override
protected void onPreExecute() {
}
#Override
protected String doInBackground(Void... String) {
//I get a complete JSON string and assign to resp HERE.
resp = getResponse();
return null;
}
#Override
protected void onPostExecute(String s) {
//pass resp to display results
displayResults(resp);
}
}
public String getResponse(){
String clientSecret = getResources().getString(R.string.client_secret);
String clientID = getResources().getString(R.string.client_id);
String url = "https://api.foursquare.com/v2/venues/explore?ll="
+ mLatitude + "," + mLongitude
+ "&limit=" + 5
+ "&radius=" + mRadius
+ "&query=" + mTerm
+ "&oauth_token="
+ "&client_secret="+ clientSecret
+ "&client_id="+ clientID
+ "&v=20150610";
String getResponseString = "";
try{
URL searchUrl = new URL(url);
HttpURLConnection httpsClient =
(HttpURLConnection) searchUrl.openConnection();
BufferedReader reader = new BufferedReader(new InputStreamReader(httpsClient.getInputStream()));
try{
getResponseString = "";
while((getResponseString = reader.readLine()) != null){
Log.d("Response ==== ", getResponseString);
}
}catch (Exception e){
e.printStackTrace();
}finally {
if(reader != null){
try{
reader.close();
}catch (Exception e){
e.printStackTrace();
}
}
}
}catch (Exception e){
e.printStackTrace();
}
return getResponseString;
}
public void displayResults(String resp){
//HERE is where it fails. The String resp becomes null/empty
// have tried logging resp, the log doesn't show up at all
// because of this, JSON string can not be parsed!!!!
try {
JSONObject json = new JSONObject(resp);
JSONArray items = json.getJSONObject("response")
.getJSONArray("groups").getJSONObject(0)
.getJSONArray("items");
//randomize items
JSONObject item = items.getJSONObject(getRandomIndex(items.length()-1));
String name = item.getJSONObject("venue").optString("name");
String categorie = item.getJSONObject("venue").getJSONArray("categories").getJSONObject(0).getString("name");
String latitude = item.getJSONObject("venue").getJSONObject("location").optString("lat");
String longitude = item.getJSONObject("venue").getJSONObject("location").optString("lng");
String image = "http://maps.google.com/maps/api/staticmap?center="
+ latitude + "," + longitude
+ "&markers=size:tiny%color:red%7C" + latitude + "," + longitude
+"&zoom=17&size=375x225&sensor=false";
mLocationView.loadUrl(image);
mBusinessName.setText(name);
mCategorie.setText(categorie);
} catch (JSONException e) {
e.printStackTrace();
}
}
EDIT: The variable resp becomes null/empty inside the function displayResults(). I don't know how this is happening.
Your getResponse() method does nothing. You need to change it so that it actually returns the complete string.
try{
StringBuilder sb = new StringBuilder();
getResponseString = "";
while((getResponseString = reader.readLine()) != null){
Log.d("Response ==== ", getResponseString);
sb.append(getResponseString);
}
}catch (Exception e){
e.printStackTrace();
}finally {
if(reader != null){
try{
reader.close();
}catch (Exception e){
e.printStackTrace();
}
}
}
return sb.toString();
I am trying to implement vtiger's API to connect my android application to it's server. I have added the API to the libs folder and then compile the .jar file. I then use the documentation to connect to the server in java.
boolean result = true;
WSClient client = new WSClient("http://en.vtiger.com/wip");
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_my);
result = client.doLogin("username", "Accesskey");
if(!result)
{
System.out.println("Login failed!");
System.out.println(client.lastError());
}
else
{
System.out.println("Login Successful");
}
}
However, I always get the Login failed and no error present. The problem is that when I open the WSClient.java class from inside the .jar, the program states that no sources can be found. I have downloaded these files from http://forge.vtiger.com/frs/?group_id=181&release_id=573 and do not know what to attach as a source. Maybe this is why I cannot connect to the server since I am using the right username and access key supplied by vtiger.
Try this:-
Its an example based on https://demo.vtiger.com/ for login
public class Login extends Activity {
//URL to get JSON Array
private static String url = "https://demo.vtiger.com/webservice.php?operation=getchallenge&username=admin";
//JSON Node Names
private static final String TAG_RESULT = "result";
private static final String TAG_TOKEN = "token";
// contacts JSONArray
JSONArray contacts = null;
String token = null;
String sessionId;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.login);
if (android.os.Build.VERSION.SDK_INT > 9) {
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
}
new AsyncTask<Void, Void, Void>() {
private ProgressDialog dialog = new ProgressDialog(Login.this);
protected void onPreExecute() {
dialog.setMessage("Loging In... Please wait...");
dialog.show();
}
#SuppressWarnings("unused")
JSONObject result;
#Override
protected Void doInBackground(Void... params) {
// Creating new JSON Parser
JSONParser jParser = new JSONParser();
// Getting JSON from URL
JSONObject json = jParser.getJSONFromUrl(url);
try {
// Getting JSON Array
result = json.getJSONObject(TAG_RESULT);
JSONObject json_result = json.getJSONObject(TAG_RESULT);
// Storing JSON item in a Variable
token = json_result.getString(TAG_TOKEN);
//Importing TextView
} catch (JSONException e) {
e.printStackTrace();
}
String username="admin";
String accesskeyvalue = "w9OweWKUS4a5sSL";
String accessKey=md5(token + accesskeyvalue);
//For debugging purpose only
//System.out.println(accesskeyvalue);
//System.out.println(token);
//System.out.println(accessKey);
String data = null;
try {
data = URLEncoder.encode("username", "UTF-8")
+ "=" + URLEncoder.encode(username, "UTF-8");
data += "&" + URLEncoder.encode("accessKey", "UTF-8") + "="
+ URLEncoder.encode(accessKey, "UTF-8");
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
String text = "";
BufferedReader reader=null;
//System.out.println(data);
// Send data
try
{
// Defined URL where to send data
URL url = new URL("https://demo.vtiger.com/webservice.php?operation=login");
// Send POST data request
URLConnection conn = url.openConnection();
conn.setDoOutput(true);
OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());
wr.write( data );
wr.flush();
// Get the server response
reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
StringBuilder sb = new StringBuilder();
String line = null;
// Read Server Response
while((line = reader.readLine()) != null)
{
// Append server response in string
sb.append(line + "\n");
}
text = sb.toString();
}
catch(Exception ex)
{
}
finally
{
try
{
reader.close();
}
catch(Exception ex) {}
}
// Show response
System.out.println(text);
sessionId = text.substring(41, 62);
//System.out.println("doInBackground()"+sessionId);
return null;
}
#Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
dialog.dismiss();
}
}.execute();
}
public String md5(String s)
{
MessageDigest digest;
try
{
digest = MessageDigest.getInstance("MD5");
digest.update(s.getBytes(),0,s.length());
String hash = new BigInteger(1, digest.digest()).toString(16);
return hash;
}
catch (NoSuchAlgorithmException e)
{
e.printStackTrace();
}
return "";
}
Change the variables as per your need
you don't need to use any additional jar files.
I have an android app that I am programming to post an array of data to a php file in local server. The data is in the format as bellow.
Name1->Quantity1
Name2->Qunatity2
I am trying to send it as json array but the problem is that whenever I am sending the data it shows that it is successful in posting that data. However i am not able to see any change of database that was suppose to be as a result of data that was sent form the android app. I will be thankful if someone guides or solves this problem of mine. please help me in this.
Bellow are the classes i am using to send and receive data
This is the class which is sending the data
public class Thirdscreen extends Activity {
private static String url = "http://10.0.2.2/bootstrap-dist/postingdata.php";
public ArrayList<QantityModelProduct> quantitymodel=new ArrayList<QantityModelProduct>();
// Progress Dialog
private ProgressDialog pDialog;
// Json parser object
JSONParser jsonParser = new JSONParser();
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.thirdscreen);
QantityModelProduct qmp;
TextView showCartContent = (TextView) findViewById(R.id.showCart);
TextView showCarttotal = (TextView) findViewById(R.id.showtotal);
Button btn = (Button) findViewById(R.id.subtractQuantity);
final Controller aController = (Controller) getApplicationContext();
int cartSize = aController.getCart().getCartSize();
String showString = "";
int total = 0;
for (int i = 0; i < cartSize; i++) {
String pName = aController.getCart().getProducts(i)
.getProductName();
int pPrice = aController.getCart().getProducts(i).getProductPrice();
int quantity = aController.getCart().getProducts(i)
.getProductQuantity();
int dataProQuantityStore = aController.getCart()
.getProducts(i).getDatabaseProductQuantity();
String pDisc = aController.getCart().getProducts(i)
.getProductDesc();
total = total + (pPrice * quantity);
showString += "\n\nProduct Name : " + pName + "\n" + "Price : "
+ pPrice + "\t" + "Quantity: " + quantity + "\n"
+ "Discription : " + pDisc + ""
+ "\n -----------------------------------";
//databaseQuantity-Current quantity
int finalVal = dataProQuantityStore - quantity;
String finalstringValue=""+finalVal;
qmp=new QantityModelProduct(pName,finalstringValue);
quantitymodel.add(qmp);
}
showCarttotal.setText("Your Total is: " + total + "Tk");
showCartContent.setText(showString);
final int productSize=quantitymodel.size();
Toast.makeText(getApplicationContext(),"Array size: "+productSize, Toast.LENGTH_SHORT).show();
btn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
new getQuantity().execute();
}
});
}
class getQuantity extends AsyncTask<String, String, String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(Thirdscreen.this);
pDialog.setMessage("Processing your request..");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
#Override
protected String doInBackground(String... params) {
JSONArray jsonArray = new JSONArray();
for (int i=0; i < quantitymodel.size(); i++) {
jsonArray.put(quantitymodel.get(i).getJSONObject());
}
jsonParser.getandpostJSONFromUrl(url, "POST",jsonArray);
return null;
}
#Override
protected void onPostExecute(String file_url) {
final Controller aController = (Controller) getApplicationContext();
// dismiss the dialog once done
pDialog.dismiss();
aController.getCart().clearCart();
aController.getProductsArraylist().clear();
Toast.makeText(getBaseContext(), "I am in second loop", Toast.LENGTH_SHORT).show();
Intent i = new Intent(getBaseContext(), FirstScreen.class);
finish();
startActivity(i);
}
}
}
public class QantityModelProduct {
private String ProductName;
private String ProductQuantity;
public QantityModelProduct(String productName, String productQuantity) {
ProductName = productName;
ProductQuantity = productQuantity;
}
public JSONObject getJSONObject() {
JSONObject obj = new JSONObject();
try {
obj.put("Name", ProductName);
obj.put("Quantity", ProductQuantity);
} catch (Exception e) {
e.printStackTrace();
}
return obj;
}
}
The following is the Json Parser Class
public class JSONParser {
static InputStream is = null;
static JSONObject jObj = null;
static String json = "";
// constructor
public JSONParser() {
}
public JSONObject getandpostJSONFromUrl(String url, String method,JSONArray name) {
// Making HTTP request
try {
// defaultHttpClient
if (method == "POST") {
// request method is POST
// defaultHttpClient
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
httpPost.setEntity(new StringEntity(name.toString()));
HttpResponse httpResponse = httpClient.execute(httpPost);
httpPost.setHeader("jsonArray",json.toString());
HttpEntity httpEntity = httpResponse.getEntity();
int response = httpResponse.getStatusLine().getStatusCode();
is = httpEntity.getContent();
Log.e("posting Status", "Post status: " + response);
}
if (method == "GET") {
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();
}
if (method == "POST") {
try {
BufferedReader reader = new BufferedReader(
new InputStreamReader(is));
} catch (Exception e) {
Log.e("Buffer error", "Buffer error" + e);
}
} else if (method == "GET") {
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("Buffer Error", "Error converting result " + e.toString());
}
// try parse the string to a JSON object
try {
jObj = new JSONObject(json);
} catch (JSONException e) {
Log.e("JSON Parser", "Error parsing data " + e.toString());
}
}
// return JSON String
return jObj;
}
}
and lastly the php file that is suppose to receive those datas.
?php
define('DB_NAME', 'sshop');
define('DB_USER', 'root');
define('DB_PASSWORD', '');
define('DB_HOST', 'localhost');
$link = mysql_connect(DB_HOST,DB_USER,DB_PASSWORD);
if(!$link){
die('could not connect: '.msql_error());
}
$db_selected=mysql_select_db(DB_NAME, $link);
if(!$db_selected){
die('Can not use '.DB_NAME.':'.mysql_error());
}
if (isset($_POST['jsonArray'])){
$jArray = json_decode($jsonArray,true);
foreach ($jArray['jsonArray'] as $obj) {
$ProductName = $obj['Name']; //String
$ProductQuantity= $obj['Quantity'];
$sql="Update productlist Set Quantity='$ProductQuantity' where Name='$ProductName';";
echo $ProductName." ".$ProductQuantity;
}
}else {
echo 'empty';
}
?>
Firstly, you should not be comparing strings using ==
Try this!
if (method.equals("POST"))
Next, to debug, see what data you are sending via the Android app to the PHP webservice, by sending the same request as response. So you know exactly if you are sending the data.
If the above step works fine, means the issue is on the PHP end. Use http://hurl.it or Postman client in Chrome to do a Post via browser, and then debug the PHP code. See if the data is being inserted.
This should solve your problem.
Nithin
In a Java Class, I have three List as fields in a class.
So I believe I made them available to the whole class? and all inner classes?
However, this does not work:
(For the example, I will only show one list here, not all three)
class Items extends ListActivity {
List<String> items = null; // field
Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// stuff
items = new ArrayList<String>();
new Task().execute();
Log.d("Size", String.valueOf(items.size()));
}
class Task extends AsyncTask<String, String, Void> {
// in this subclass, I parse items from JSON and add to List "items".
items = add(item);
}
Once I exit the task, I seem to lose the items in the List. It Logs "size 0"; if I do it inside the task, it shows the proper amount of items. Am I missing a very basic point about the scope of List variables here?
EDIT: Below is the complete Task class (slightly cleaned up for posting)
class Task extends AsyncTask<String, String, Void> {
private InputStream is = null;
private String result = "";
#Override
protected Void doInBackground(String... params) {
String url_select = "items.php";
param = new ArrayList<NameValuePair>();
param.add(new BasicNameValuePair("category", Category));
HttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url_select);
try {
httpPost.setEntity(new UrlEncodedFormEntity(param));
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
// read content
is = httpEntity.getContent();
} catch (Exception e) {
Log.e("log_tag", "Error in http connection " + e.toString());
}
try {
BufferedReader br = new BufferedReader(
new InputStreamReader(is));
StringBuilder sb = new StringBuilder();
String line = "";
while ((line = br.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
result = sb.toString();
} catch (Exception e) {
// TODO: handle exception
Log.e("log_tag", "Error converting result " + e.toString());
}
return null;
}
protected void onPostExecute(Void v) {
try {
JSONArray jArray = new JSONArray(result);
JSONObject json_data = null;
for (int i = 0; i < jArray.length(); i++) {
json_data = jArray.getJSONObject(i);
item = json_data.getString("item");
items.add(item);
Log.d("Items", item);
}
} catch (JSONException e1) {
Toast.makeText(getBaseContext(), "No items!",
Toast.LENGTH_SHORT).show();
} catch (ParseException e1) {
e1.printStackTrace();
}
}
}
I am not Android developer but isn't AsyncTask something like new Thread? If yes then you just see "size 0" because Log.d("Size", String.valueOf(items.size())); was executed before new task().execute(); updated your list.
You'll want to read through this tutorial
Basically, the default access level is package private (I could be wrong on the description), but basically it means that so long as you're in the same package you can see the member, but it is not visible to sub classes.
Try using the protected access level instead