I Want to know how to connect database........? - android

I am new for Android i want to know how to connect database.I saw one video in you tube and i follow hole video but its not working.i don't know where i made mistake. please help me.from one week an words i'm trying but now also i'm not getting solution please help me stack over flow.
class ServerRequests {
ProgressDialog progressDialog;
public static final int CONNECTION_TIMEOUT=1000*15;
public static final String
SERVER_ADDRESS="http://192.168.1.11/myfolder/new1.php";
public ServerRequests(Context context){
progressDialog=new ProgressDialog(context);
progressDialog.setCancelable(false);
progressDialog.setTitle("processing");
progressDialog.setMessage("please wait.....");
}
public void storeUserDataInBackground(User user,GetUserCallbackuserCallback{
progressDialog.show();
new StoreUserDataAsyncTask(user,userCallback).execute();
}
public void fetchUserDataInBackground(User user,GetUserCallback callBack){
progressDialog.show();
new fetchUserDataAsynctask(user,callBack).execute();
}
public class StoreUserDataAsyncTask extends AsyncTask<Void,Void,Void>{
User user;
GetUserCallback userCallback;
public StoreUserDataAsyncTask(User user,GetUserCallback userCallback){
this.user=user;
this.userCallback=userCallback;
}
#Override
protected Void doInBackground(Void... params) {
ArrayList<NameValuePair>dataToSend=new ArrayList<>();
dataToSend.add(new BasicNameValuePair("name",user.name));
dataToSend.add(new BasicNameValuePair("age",user.age + ""));
dataToSend.add(new BasicNameValuePair("username",user.username));
dataToSend.add(new BasicNameValuePair("password",user.password));
HttpParams httpRequestParams = new BasicHttpParams();
HttpConnectionParams.setConnectionTimeout(httpRequestParams,CONNECTION_TIMEOUT);
HttpConnectionParams.setSoTimeout(httpRequestParams,CONNECTION_TIMEOUT);
HttpClient client = new DefaultHttpClient(httpRequestParams);
HttpPost post = new HttpPost(SERVER_ADDRESS + "Register.php");
try{
post.setEntity(new URLEncoderFormEntity(dataToSend));
client.execute(post);
}catch (Exception e){
e.printStackTrace();
}
return null;
}
#Override
protected void onpostExecute(Void aVoid){
progressDialog.dismiss();
userCallback.done(null);
super.onPostExecute(aVoid);
}
}
public fetchUserDataAsyncTask extends AsyncTask<Void,Void,User>{
User user;
GetUserCallback userCallback;
public fetchUserDataAsyncTask(User user,GetUserCallback userCallback){
this.user=user;
this.userCallback = userCallback;
}
#Override
protected User doInBackground(Void... params){
ArrayList<NameValuePair>dataToSend=new ArrayList<>();
dataToSend.add(new BasicNameValuePair("username",user.username));
dataToSend.add(new BasicNameValuePair("password",user.password));
HttpParams httpRequestParams = new BasicHttpParams();
HttpConnectionParams.setConnectionTimeout(httpRequestParams, CONNECTION_TIMEOUT);
HttpConnectionParams.setSoTimeout(httpRequestParams, CONNECTION_TIMEOUT);
HttpClient client = new DefaultHttpClient(httpRequestParams);
HttpPost post = new HttpPost(SERVER_ADDRESS + "FetchUserData.php");
User returnedUser=null;
try{
post.setEntity(new URLEncoderFormEntity(dataToSend));
HttpResponce httpResponce=client.execute(post);
HttpEntity entity=httpResponce.getEntity();
String result= EntityUtils.toString(entity);
JSONObject jObject=new JSONObject(result);
if (jObject.length()==0){
user=null;
}else{
String name=jObject.getString("name");
int age =jObject.getInt("age");
returnedUser=new User(name,age,user.username,user.password);
}
}catch (Exception e){
e.printStackTrace();
}
return returnedUser;
}
#Override
protected void onPostExecute(User returnedUser){
progressDialog.dismiss();
userCallback.done(null);
super.onPostExecute(returnedUser);
}
}
}
enter code here
public class LoginActivity extends AppCompatActivity implements View.OnClickListener {
Button blogin;
EditText etusername,etpassword;
TextView tvregister;
UserLocalStore userLocalStore;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.login);
etusername=(EditText)findViewById(R.id.username_edit);
etpassword=(EditText)findViewById(R.id.password_edit);
blogin=(Button)findViewById(R.id.login_button);
tvregister=(TextView)findViewById(R.id.tv_register);
blogin.setOnClickListener(this);
tvregister.setOnClickListener(this);
userLocalStore=new UserLocalStore(this);
}
#Override
public void onClick(View v) {
switch (v.getId()){
case R.id.login_button:
String username=etusername.getText().toString();
String password=etpassword.getText().toString();
User user=new User(username,password);
authenticate(user);
userLocalStore.storeUserData(user);
userLocalStore.setUserLoggedIn(true);
break;
case R.id.tv_register:
startActivity(new Intent(this,RegisterActivity.class));
break;
}
}
private void authenticate(User user) {
ServerRequests serverRequests = new ServerRequests(this);
serverRequests.fetchUserDataInBackground(user, new GetUserCallback() {
#Override
public void done(User returnedUser) {
if (returnedUser == null) {
showErrorMessage();
}else {
logUserIn(returnedUser);
}
}
});
}
private void showErrorMessage() {
AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(LoginActivity.this);
dialogBuilder.setMessage("Incorrect user details");
dialogBuilder.setPositiveButton("ok", null);
dialogBuilder.show();
}
private void logUserIn(User returnedUser){
userLocalStore.storeUserData(returnedUser);
userLocalStore.setUserLoggedIn(true);
startActivity(new Intent(this,MainActivity.class));
}
}

Here is the link which you can refer for fetching data from server.
For Creating Web Service using PHP Click here
<?php
include("connect.php");
$result="";
//get data from users (name for user variable is p1 and p2
//here I am stroing this value to par1 and par2
//method i am using is GET
$par1=$_GET['p1'];
$par2=$_GET['p2'];
$eve = "select * from table where field1='$par1' and field2='$par2'";
$re = mysql_query($eve);
$response = array();
$posts = array();
while($rt = mysql_fetch_array($re))
{
$f1=$rt['field1'];
$f2=$rt['field2'];
break;
}
$posts[] = array('p1'=> $f1,'p2'=> $f2);
$response['posts'] = $posts;
echo stripslashes(json_encode( array('item' => $posts)));
?>
For AsyncTask Example Click here
import android.app.ProgressDialog;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.AsyncTask;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
public class Login extends AppCompatActivity {
boolean remember;
private ProgressDialog pDialog;
public static final String PREFS_NAME = "Preference";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
((Button) findViewById(R.id.btnlogin)).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//Login Validation
try {
pDialog = new ProgressDialog(Login.this);
pDialog.setMessage("Verifying...");
pDialog.show();
LoginVerifyTask g = new LoginVerifyTask();
g.execute(((EditText) findViewById(R.id.mobile)).getText().toString(), ((EditText) findViewById(R.id.password)).getText().toString());
} catch (Exception e) {
Log.e("cs", "catch error");
}
}
});
((TextView) findViewById(R.id.newuserregistrationtxtview)).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent i = new Intent(getApplicationContext(), Registration1.class);
startActivity(i);
}
});
}
public class LoginVerifyTask extends AsyncTask<String, Void, String>
{
String u,p;
void LoginActivity(String s)
{
}
#Override
protected void onPostExecute(String json) {
// TODO Auto-generated method stub
pDialog.dismiss();
pDialog = null;
if (json == null)
{
return;
}
String csv="";
try {
JSONObject js = new JSONObject(json);
JSONArray user = js.getJSONArray("item");
for(int i=0;i<user.length();i++)
{
JSONObject j2 = user.getJSONObject(i);
//received data
String result = j2.get("p1").toString();
break;
}
}
catch(JSONException js)
{
}
return;
}
#Override
protected String doInBackground(String... params) {
// TODO Auto-generated method stub
u = params[0];
p = params[1];
String tempdata="";
String buffer="";
try
{
URL url = new URL("http://websitename.com/folder/webservice.php?p1=" + params[0].replace(" ", "%20") + "&p2=" + params[1].replace(" ", "%20"));
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
conn.connect();
InputStream is = conn.getInputStream();
//buffer = new String();
if(is==null)
{
return tempdata;
}
else
{
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
String line="";
while( (line = reader.readLine())!=null)
{
buffer += line;
}
return buffer;
}
}
catch(Exception e)
{
Log.e("cs", e.toString());
}
return buffer;
}
}
}

Related

Progressbar with Async Task while trying to connect to server

I want to show Progress Dialog when background task is executed by doInbackground Method of AsyncTask Class, But the problem is when my server is off (Wamp server turns off) it doesnot shows Progress Dialog when trying to get connected with the server.
Please Help in this regard.
Main Class:
import android.app.AlertDialog;
import android.database.Cursor;
import android.os.Bundle;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ProgressBar;
import android.widget.Spinner;
import android.widget.Toast;
import java.util.Calendar;
import java.util.Date;
import java.text.SimpleDateFormat;
import java.util.concurrent.ExecutionException;
public class MainActivity extends AppCompatActivity{
Button btnSubmitOrder;
EditText edDealerID;
EditText edProductID;
EditText edQuantity;
String stDealerID;
String stProductID;
String stQuantity;
String stUnit;
String stDate;
String stTime;
String stStatus;
ProgressBar edProgress;
Date currentDate = Calendar.getInstance().getTime();
DatabaseSQLite objDatabaseSqlite;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Date objDate = Calendar.getInstance().getTime();
SimpleDateFormat df = new SimpleDateFormat("dd/MMM/yyyy");
stDate = df.format(objDate);
SimpleDateFormat sdf = new SimpleDateFormat("hh:mm a");
stTime = sdf.format(objDate);
final Spinner dropdown = findViewById(R.id.edit_unit);
String[] items = new String[]{"Box", "Packets"};
ArrayAdapter<String> adapter = new ArrayAdapter<>(this, android.R.layout.simple_spinner_dropdown_item, items);
dropdown.setAdapter(adapter);
objDatabaseSqlite = new DatabaseSQLite(this);
btnSubmitOrder = findViewById(R.id.btn_submitorder);
edDealerID = findViewById(R.id.edit_dealerid);
edProductID = findViewById(R.id.edit_productid);
edQuantity = findViewById(R.id.edit_quantity);
edProgress = findViewById(R.id.ed_progress);
btnSubmitOrder.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
stDealerID = edDealerID.getText().toString();
stProductID = edProductID.getText().toString();
stQuantity = edQuantity.getText().toString();
stUnit = dropdown.getSelectedItem().toString();
stStatus = "Pending";
BackgroundTask objBackground = new BackgroundTask(MainActivity.this);
try {
String response = objBackground.execute(stDealerID, stProductID, stQuantity, stUnit, stDate, stTime, stStatus).get();
} catch (ExecutionException e) {
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
});
}
}
BackgroundTask Class:
import android.app.ProgressDialog;
import android.content.Context;
import android.os.AsyncTask;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLEncoder;
/**
* Created by Saffi on 3/17/2016.
*/
public class BackgroundTask extends AsyncTask<String,Void,String> {
private String response = "";
private ProgressDialog dialog;
Context ctx;
BackgroundTask(Context ctx)
{
this.ctx = ctx;
}
#Override
protected void onPreExecute() {
dialog = new ProgressDialog(ctx);
dialog.setMessage("Progress start");
dialog.show();
}
protected String doInBackground(String... params) {
String sendInvoice = "http://10.0.2.2/YounasTraders/SendInvoice.php";
String dealerId = params[0];
String productId = params[1];
String quantity = params[2];
String unit = params[3];
String date = params[4];
String time = params[5];
String status = params[6];
try {
URL objurl = new URL(sendInvoice);
HttpURLConnection objhttpurlconnection = (HttpURLConnection) objurl.openConnection();
objhttpurlconnection.setRequestMethod("POST");
objhttpurlconnection.setDoOutput(true);
objhttpurlconnection.setDoInput(true);
OutputStream objos = objhttpurlconnection.getOutputStream();
BufferedWriter objbuffwrite = new BufferedWriter(new OutputStreamWriter(objos, "UTF-8"));
String data = URLEncoder.encode("dealer_id", "UTF-8") +"="+URLEncoder.encode(dealerId, "UTF-8")+"&"+
URLEncoder.encode("product_id", "UTF-8")+"="+URLEncoder.encode(productId, "UTF-8")+"&"+
URLEncoder.encode("quantity", "UTF-8")+"="+URLEncoder.encode(quantity, "UTF-8")+"&"+
URLEncoder.encode("unit", "UTF-8")+"="+URLEncoder.encode(unit, "UTF-8")+"&"+
URLEncoder.encode("date", "UTF-8")+"="+URLEncoder.encode(date, "UTF-8")+"&"+
URLEncoder.encode("time", "UTF-8")+"="+URLEncoder.encode(time, "UTF-8")+"&"+
URLEncoder.encode("status", "UTF-8")+"="+URLEncoder.encode(status, "UTF-8");
objbuffwrite.write(data);
objbuffwrite.flush();
objbuffwrite.close();
objos.close();
InputStream objis = objhttpurlconnection.getInputStream();
objis.close();
objhttpurlconnection.disconnect();
response = "Order Sent Successfully";
return response;
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
response = "Order Not Sent Successfully";
return response;
}
#Override
protected void onProgressUpdate(Void... values) {
super.onProgressUpdate(values);
dialog.show();
}
#Override
protected void onPostExecute(String value) {
dialog.dismiss();
}
}
The problem is you are executing a task on main thread using .get method
The first change your AsyncTask task include this callback interface to call it after finishing your HTTP request
public class BackgroundTask extends AsyncTask {
private CallBack callBack;
public CallBack getCallBack() {
return callBack;
}
public void setCallBack(CallBack callBack) {
this.callBack = callBack;
}
private String response = "";
private ProgressDialog dialog;
Context ctx;
BackgroundTask(Context ctx)
{
this.ctx = ctx;
}
#Override
protected void onPreExecute() {
dialog = new ProgressDialog(ctx);
dialog.setMessage("Progress start");
dialog.show();
}
protected String doInBackground(String... params) {
String sendInvoice = "http://10.0.2.2/YounasTraders/SendInvoice.php";
String dealerId = params[0];
String productId = params[1];
String quantity = params[2];
String unit = params[3];
String date = params[4];
String time = params[5];
String status = params[6];
try {
URL objurl = new URL(sendInvoice);
HttpURLConnection objhttpurlconnection = (HttpURLConnection) objurl.openConnection();
objhttpurlconnection.setRequestMethod("POST");
objhttpurlconnection.setDoOutput(true);
objhttpurlconnection.setDoInput(true);
OutputStream objos = objhttpurlconnection.getOutputStream();
BufferedWriter objbuffwrite = new BufferedWriter(new OutputStreamWriter(objos, "UTF-8"));
String data = URLEncoder.encode("dealer_id", "UTF-8") +"="+URLEncoder.encode(dealerId, "UTF-8")+"&"+
URLEncoder.encode("product_id", "UTF-8")+"="+URLEncoder.encode(productId, "UTF-8")+"&"+
URLEncoder.encode("quantity", "UTF-8")+"="+URLEncoder.encode(quantity, "UTF-8")+"&"+
URLEncoder.encode("unit", "UTF-8")+"="+URLEncoder.encode(unit, "UTF-8")+"&"+
URLEncoder.encode("date", "UTF-8")+"="+URLEncoder.encode(date, "UTF-8")+"&"+
URLEncoder.encode("time", "UTF-8")+"="+URLEncoder.encode(time, "UTF-8")+"&"+
URLEncoder.encode("status", "UTF-8")+"="+URLEncoder.encode(status, "UTF-8");
objbuffwrite.write(data);
objbuffwrite.flush();
objbuffwrite.close();
objos.close();
InputStream objis = objhttpurlconnection.getInputStream();
objis.close();
objhttpurlconnection.disconnect();
response = "Order Sent Successfully";
return response;
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
response = "Order Not Sent Successfully";
return response;
}
#Override
protected void onProgressUpdate(Void... values) {
super.onProgressUpdate(values);
dialog.show();
}
#Override
protected void onPostExecute(String value) {
dialog.dismiss();
if(callBack != null)
callBack.onResult(value);
}
public interface CallBack{
void onResult(String value);
}
}
Second change execution of your async task, get result on callback
BackgroundTask objBackground = new BackgroundTask(MainActivity.this);
objBackground.setCallBack(new BackgroundTask.CallBack() {
#Override
public void onResult(String value) {
//get here your response
}
});
objBackground.execute(stDealerID, stProductID, stQuantity, stUnit, stDate, stTime, stStatus);

How to Delete a record from the DataBase mysql &Screen while Clicked on ListView item?

I want to Delete a record from the database when i click on the Buttton.
The Button i set in the listView.
I want to perfrom this on ListView Here i tried following way but its not working..
Here My API
<?php
include("connection.php");
$tbl = "abc";
$idToDelete = $_GET["id"];
$delete_row = mysql_query("DELETE FROM $tbl WHERE o_id=".$idToDelete);
$response["delete"] = array();
$response["success"]=1;
// push single product into final response array
echo json_encode($response);
?>
ListviewAdapter.java
package com.example.sachin.alertbox;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ActionMenuView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.Spinner;
import android.widget.Toast;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
public class MainActivity extends AppCompatActivity {
Button add;
Spinner spinner;
ListView listview;
LinearLayout linearlayout;
JSONObject jsonobject;
private static String url_addevent = "http ://10.0.2.2/portal/order_product.php";
public static String url_visitor= "http://10.0.2.2/portal/fetchorder_of_user.php";
JSONParser jParser = new JSONParser();
JSONArray ownerObj;
ArrayList<HashMap<String, String>> arraylist;
ArrayList<String> delivery_fetch = new ArrayList<String>();
ListViewAdapterorder listadapter;
EditText qty;
LinearLayout layout;
ActionMenuView.LayoutParams params;
LinearLayout mainLayout;
PopupWindow popUp;
final Context context = this;
ArrayAdapter<String> adapter;
Button Delete;
ArrayList<String> listItems = new ArrayList<>();
String stringqty,stringspinner;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
add = (Button) findViewById(R.id.clickme);
popUp = new PopupWindow(this);
layout = new LinearLayout(this);
mainLayout = new LinearLayout(this);
listview = (ListView)findViewById(R.id.listview);
Delete=(Button)findViewById(R.id.delete);
add.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
LayoutInflater li = LayoutInflater.from(context);
View promptsView = li.inflate(R.layout.prompts, null);
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(context);
// set prompts.xml to alertdialog builder
alertDialogBuilder.setView(promptsView);
spinner=(Spinner)promptsView.findViewById(R.id.spinner);
adapter = new ArrayAdapter<String>(getApplication(), R.layout.spinner_layout, R.id.txt, listItems);
spinner.setAdapter(adapter);
spinner.setSelection(0);
qty=(EditText)promptsView.findViewById(R.id.qty);
// set dialog message
alertDialogBuilder
.setCancelable(false)
.setPositiveButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
// get user input and set it to result
// edit text
stringqty=qty.getText().toString();
stringspinner=spinner.getSelectedItem().toString();
addvisitor();
new fetchorder().execute();
Toast.makeText(getApplicationContext(), "qty : " + stringqty +stringspinner, Toast.LENGTH_SHORT).show();
}
})
.setNegativeButton("Cancel",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.cancel();
}
});
// create alert dialog
AlertDialog alertDialog = alertDialogBuilder.create();
// show it
alertDialog.show();
}
});
}
private void addvisitor() {
service(stringqty,stringspinner);
}
private void service(String qty,String sp) {
class AddVisitclass extends AsyncTask<String, Void, String> {
ProgressDialog loading;
RegisterUserClass ruc = new RegisterUserClass();
//#Override
protected void onPreExecute() {
// Create a progressdialog
super.onPreExecute();
//loading = ProgressDialog.show(getApplicationContext(), "Please Wait...!!!", null, true, true);
}
#Override
protected String doInBackground(String... params) {
HashMap<String, String> param = new HashMap<String, String>();
param.put("quantity", params[0]);
param.put("model", params[1]);
String result = ruc.sendPostRequest(url_addevent, param);
Log.d("Result", result);
Log.d("Data", param.toString());
return result;
}
//#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
//loading.dismiss();
Toast.makeText(getApplicationContext(), "Service Added Successfully...!!!", Toast.LENGTH_LONG).show();
/* Intent i1 = new Intent(getApplicationContext(), HomeActivity.class);
startActivity(i1);*/
}
}
AddVisitclass regi = new AddVisitclass();
regi.execute(qty,sp);
}
ArrayList<String> o_aid= new ArrayList<String>();
ArrayList<String> o_aproduct= new ArrayList<String>();
ArrayList<String> o_aqty= new ArrayList<String>();
ArrayList<String> o_atotal= new ArrayList<String>();
private class fetchorder extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected Void doInBackground(Void... args) {
try {
arraylist = new ArrayList<HashMap<String, String>>();
List<NameValuePair> params = new ArrayList<NameValuePair>();
// params.add(new BasicNameValuePair("v_username", uid));
JSONObject json = jParser.makeHttpRequest(url_visitor, "GET", params);
int success1 = Integer.parseInt(json.getString("success4"));
Log.d("success4", json.toString());
if (success1 == 0) {}
if (success1 == 1) {
o_aid.clear();
o_aproduct.clear();
o_aqty.clear();
o_atotal.clear();
ownerObj = json.getJSONArray("visit");
for (int i = 0; i < ownerObj.length(); i++) {
jsonobject = ownerObj.getJSONObject(i);
o_aid.add(jsonobject.getString("o_id"));
o_aproduct.add(jsonobject.getString("o_product"));
o_aqty.add(jsonobject.getString("o_qty"));
o_atotal.add(jsonobject.getString("o_total"));
}
}
} catch (Exception e) {
}
return null;
}
#Override
protected void onPostExecute(Void args) {
// Locate the listview in listview_main.xml
if (listadapter == null) {
listadapter = new ListViewAdapterorder(getApplicationContext(), o_aid, o_aproduct, o_aqty, o_atotal);
listview.setAdapter(listadapter);
} else {
listadapter.notifyDataSetChanged();
}
}
}
public void onStart() {
super.onStart();
BackTask bt = new BackTask();
bt.execute();
}
private class BackTask extends AsyncTask<Void, Void, Void> {
ArrayList<String> list;
protected void onPreExecute() {
super.onPreExecute();
list = new ArrayList<>();
}
protected Void doInBackground(Void... params) {
InputStream is = null;
String result = "";
try {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://10.0.2.2/portal/spinner.php");
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
// Get our response as a String.
is = entity.getContent();
} catch (IOException e) {
e.printStackTrace();
}
//convert response to string
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(is, "utf-8"));
String line = null;
while ((line = reader.readLine()) != null) {
result += line;
}
is.close();
//result=sb.toString();
} catch (Exception e) {
e.printStackTrace();
}
// parse json data
try {
JSONArray jArray = new JSONArray(result);
list.add("Please Select Model");
for (int i = 0; i < jArray.length(); i++) {
JSONObject jsonObject = jArray.getJSONObject(i);
// add interviewee name to arraylist
list.add(jsonObject.getString("m_model"));
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
protected void onPostExecute(Void result) {
listItems.addAll(list);
}
}
}
Here MainActivity.java ListView class
ArrayList<String> o_aid= new ArrayList<String>();
ArrayList<String> o_aproduct= new ArrayList<String>();
ArrayList<String> o_aqty= new ArrayList<String>();
ArrayList<String> o_atotal= new ArrayList<String>();
private class fetchorder extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected Void doInBackground(Void... args) {
try {
arraylist = new ArrayList<HashMap<String, String>>();
List<NameValuePair> params = new ArrayList<NameValuePair>();
// params.add(new BasicNameValuePair("v_username", uid));
JSONObject json = jParser.makeHttpRequest(url_visitor, "GET", params);
int success1 = Integer.parseInt(json.getString("success4"));
Log.d("success4", json.toString());
if (success1 == 0) {}
if (success1 == 1) {
o_aid.clear();
o_aproduct.clear();
o_aqty.clear();
o_atotal.clear();
ownerObj = json.getJSONArray("visit");
for (int i = 0; i < ownerObj.length(); i++) {
jsonobject = ownerObj.getJSONObject(i);
o_aid.add(jsonobject.getString("o_id"));
o_aproduct.add(jsonobject.getString("o_product"));
o_aqty.add(jsonobject.getString("o_qty"));
o_atotal.add(jsonobject.getString("o_total"));
}
}
} catch (Exception e) {
}
return null;
}
#Override
protected void onPostExecute(Void args) {
// Locate the listview in listview_main.xml
if (listadapter == null) {
listadapter = new ListViewAdapterorder(getApplicationContext(), o_aid, o_aproduct, o_aqty, o_atotal);
listview.setAdapter(listadapter);
} else {
listadapter.notifyDataSetChanged();
}
}
}
I tried this way but the delete is not happening.. please suggest me some coede for this.
Try this.
Delete.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
datlist.remove(position);
o_aid.remove(position);
o_aproduct.remove(position);
o_aqty.remove(position);
o_atotal.remove(position);
Snackbar.make(view, "Record Delete Succesfully", Snackbar.LENGTH_LONG).show();
notifyDataSetChanged();
}
});
Call me:85110 51548 if any issue
There is issue in your connection.php pls check I have checked but not issue from php queries but if connection.php has issue you will not find because if record is deleted it returns 1 if any problem it returns 0 in your code return 0 it means record is not deleted successfully.
Write The Following Code in Your php and change it into connection.php
/*connection.php */
$host="your host";
$username="your user name";
$password="your password";
$dbname="your database name";
$con = new mysqli($host, $username, $password,$dbname);
// Check connection
if ($con->connect_error) {
die("Connection failed: " . $con->connect_error);
}
/*code.php */
include('connection.php');
$tbl = "abc";
$idToDelete = $_GET["id"];
$sql="DELETE FROM $tbl WHERE o_id=".$idToDelete;
$delete_row = $con->query($sql);
$response["delete"] = array();
$response["success"]=1;
/// push single product into final response array
echo json_encode($response);
** In short there is a problem in connection file thats why not deleted that record **

Force close when start intent inside postexecute()

I have create an app where after u insert some word into the edit text, it will send to the server and go to other activity.But i cant make it go to other activity as it force close.Help me please
here is my code
public class MainActivity extends AppCompatActivity implements View.OnClickListener{
private static final String SERVER_ADDRESS = "http://www.bruhnancel.xyz/testing.php";
EditText picname, link;
Button submit, submitpic;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
picname = (EditText)findViewById(R.id.picname);
link = (EditText)findViewById(R.id.link);
submit =(Button)findViewById(R.id.submit);
submitpic = (Button)findViewById(R.id.submitpic);
submit.setOnClickListener(this);
submitpic.setOnClickListener(this);
}
#Override
public void onClick(View v) {
switch (v.getId()){
case R.id.submit:
new sendData(picname.getText().toString(), link.getText().toString()).execute();
break;
case R.id.submitpic:
}
}
private HttpParams getHttpRequestParams(){
HttpParams httpRequestParams = new BasicHttpParams();
HttpConnectionParams.setConnectionTimeout(httpRequestParams, 1000 * 30);
HttpConnectionParams.setSoTimeout(httpRequestParams, 1000 * 30);
return httpRequestParams;
}
public class sendData extends AsyncTask<Void, Void, Void>{
Context c;
String picname;
String link;
/*public sendData(Context context) {
this.context = context.getApplicationContext();
}*/
public sendData(Context context) {
c = context;
}
public sendData(String picname, String link){
this.picname = picname;
this.link = link;
}
#Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
Toast.makeText(getApplicationContext(), " Uploaded", Toast.LENGTH_SHORT).show();
startActivity(new Intent(c, UploadImage.class));
}
#Override
protected Void doInBackground(Void... params) {
ArrayList<NameValuePair> dataToSend = new ArrayList<>();
dataToSend.add(new BasicNameValuePair("picname", picname));
dataToSend.add(new BasicNameValuePair("link", "www.bruhnancel.xyz/" + link));
try{
HttpParams httpRequestParams = getHttpRequestParams();
HttpClient client = new DefaultHttpClient(httpRequestParams);
HttpPost post = new HttpPost(SERVER_ADDRESS);
post.setEntity(new UrlEncodedFormEntity(dataToSend));
client.execute(post);
}catch(Exception e){
Toast.makeText(getApplicationContext(), " Failed", Toast.LENGTH_SHORT).show();
}
return null;
}
}
}
This is my UploadImageClass
package com.example.user.testinguploaddata;
import android.app.ProgressDialog;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.provider.MediaStore;
import android.support.v7.app.AppCompatActivity;
import android.util.Base64;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Toast;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import java.io.ByteArrayOutputStream;
import java.util.ArrayList;
#SuppressWarnings("ALL")
public class UploadImage extends AppCompatActivity implements View.OnClickListener {
private ProgressDialog progressDialog;
private static final int RESULT_LOAD_IMAGE = 1;
private static final String SERVER_ADDRESS = "http://www.bruhnancel.xyz/" ;
ImageView imageToUpload, downloadedImage;
Button bUploadImage, bDownloadImage;
EditText uploadImageName, downloadImageName;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
imageToUpload = (ImageView)findViewById(R.id.imageToUpload);
downloadedImage = (ImageView)findViewById(R.id.downloadedImage);
bUploadImage = (Button)findViewById(R.id.bUploadImage);
bDownloadImage = (Button)findViewById(R.id.bDownloadImage);
uploadImageName = (EditText)findViewById(R.id.etUploadName);
downloadImageName = (EditText)findViewById(R.id.etDownloadName);
imageToUpload.setOnClickListener(this);
bUploadImage.setOnClickListener(this);
bDownloadImage.setOnClickListener(this);
}
#Override
public void onClick(View v) {
switch(v.getId()){
case R.id.imageToUpload:
Intent galleryIntent = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(galleryIntent, RESULT_LOAD_IMAGE); // Bring the image together after the intent
break;
case R.id.bUploadImage:
Bitmap image = ((BitmapDrawable)imageToUpload.getDrawable()).getBitmap();
new UploadImageToServer(image, uploadImageName.getText().toString()).execute();
break;
case R.id.bDownloadImage:
break;
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(requestCode == RESULT_LOAD_IMAGE && resultCode == RESULT_OK && data !=null){
Uri selectedImage = data.getData();
imageToUpload.setImageURI(selectedImage);
}
}
private class UploadImageToServer extends AsyncTask<Void, Void, Void>{
Bitmap image;
String name;
public UploadImageToServer(Bitmap image, String name){
this.image = image;
this.name = name;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
showProgressDialog("Please wait...", "Your message");
}
#Override
protected Void doInBackground(Void... params) {
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
image.compress(Bitmap.CompressFormat.JPEG, 50, byteArrayOutputStream);
String encodedImage = Base64.encodeToString(byteArrayOutputStream.toByteArray(), Base64.DEFAULT);
ArrayList<NameValuePair> dataToSend = new ArrayList<>();
dataToSend.add(new BasicNameValuePair("image", encodedImage));
dataToSend.add(new BasicNameValuePair("name", name));
//ContentValues values = new ContentValues();
//values.put("image", encodedImage);
//values.put("name", name);
try{
HttpParams httpRequestParams = getHttpRequestParams();
HttpClient client = new DefaultHttpClient(httpRequestParams);
HttpPost post = new HttpPost(SERVER_ADDRESS + "SavePicture.php");
post.setEntity(new UrlEncodedFormEntity(dataToSend));
client.execute(post);
}catch(Exception e){
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
if(progressDialog != null && progressDialog.isShowing())
{
progressDialog.dismiss();
Toast.makeText(getApplicationContext(), "Image Uploaded", Toast.LENGTH_SHORT).show();
}
}
}
private HttpParams getHttpRequestParams(){
HttpParams httpRequestParams = new BasicHttpParams();
HttpConnectionParams.setConnectionTimeout(httpRequestParams, 1000 * 30);
HttpConnectionParams.setSoTimeout(httpRequestParams, 1000*30);
return httpRequestParams;
}
private void showProgressDialog(String title, String message)
{
progressDialog = new ProgressDialog(this);
progressDialog.setTitle("Please wait"); //title
progressDialog.setMessage("Uploading"); // message
progressDialog.setCancelable(false);
progressDialog.show();
}
}

How do i connect mysql database and insert data into it using android code

I have mysql database on my hosting server
On simple android application I have feedback form and on submit I want to insert data into mysql database which is on server .
I tried google and found this following solution for local machine
how do I connect to my hosting server and mysql database without any php code?
public void insert()
{
ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("id",id));
nameValuePairs.add(new BasicNameValuePair("name",name));
try
{
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://10.0.2.2/insert.php");
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
is = entity.getContent();
Log.e("pass 1", "connection success ");
}
catch(Exception e)
{
Log.e("Fail 1", e.toString());
Toast.makeText(getApplicationContext(), "Invalid IP Address",
Toast.LENGTH_LONG).show();
}
try
{
BufferedReader reader = new BufferedReader
(new InputStreamReader(is,"iso-8859-1"),8);
StringBuilder sb = new StringBuilder();
while ((line = reader.readLine()) != null)
{
sb.append(line + "\n");
}
is.close();
result = sb.toString();
Log.e("pass 2", "connection success ");
}
catch(Exception e)
{
Log.e("Fail 2", e.toString());
}
try
{
JSONObject json_data = new JSONObject(result);
code=(json_data.getInt("code"));
if(code==1)
{
Toast.makeText(getBaseContext(), "Inserted Successfully",
Toast.LENGTH_SHORT).show();
}
else
{
Toast.makeText(getBaseContext(), "Sorry, Try Again",
Toast.LENGTH_LONG).show();
}
}
catch(Exception e)
{
Log.e("Fail 3", e.toString());
}
}
Here
HttpPost httppost = new HttpPost("http://10.0.2.2/insert.php");
insert.php is mentioned means you have to put this file on server
just change the http://10.0.2.2/insert.php to the path of your server file path where the file is stored
Code for insert.php
// this variables is used for connecting to database and server
$host="yourhost";
$uname="username";
$pwd='pass';
$db="dbname";
// this is for connecting
$con = mysql_connect($host,$uname,$pwd) or die("connection failed");
mysql_select_db($db,$con) or die("db selection failed");
// getting id and name from the client
if(isset($_REQUEST)){
$id=$_REQUEST['id'];
$name=$_REQUEST['name'];}
// variable used to tell the client whether data is stored in database or not
$flag['code']=0;
// for insertion
if($r=mysql_query("insert into emp_info values('$name','$id') ",$con))
{
//if insertion succeed set code to 1
$flag['code']=1;
echo"hi";
}
// send result to client that will be 1 or 0
print(json_encode($flag));
//close
mysql_close($con);
?>
as mentioned in your code , this will get the value from server whether the data is stored or not by code=1 for stored and code = 0 for not stored
JSONObject json_data = new JSONObject(result);
code=(json_data.getInt("code"));
if(code==1)
{
Toast.makeText(getBaseContext(), "Inserted Successfully",
Toast.LENGTH_SHORT).show();
}
else
{
Toast.makeText(getBaseContext(), "Sorry, Try Again",
Toast.LENGTH_LONG).show();
}
package fluent.techno.shreedurgajyotish;
import java.util.ArrayList;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import fluentindia.database.mysql.JsonHelper;
import fluentindia.tech.MenuAdapter.ProductAdapter;
import fluentindia.tech.MenuModel.ProductModel;
import android.app.ProgressDialog;
import android.content.Intent;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemSelectedListener;
public class Feedback extends Fragment
{
Button close,home,btnback,btnsend;
EditText edname,edcompany,edemail,edcontact,edwebsite,edaddress,edcomment;
String na,con,email,comm,advname,advem,advcontact,nacompany,web,add;
Spinner product;
JsonHelper Jobj;
String WebUrl, UrlImg;
JSONObject obj = null;
String Id,name,em,contact,AdvocateId,city;
ProductAdapter madappppppppppp;
ArrayList<ProductModel> llistttt;
int proid=0;
TextView textViewt2,t1;
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
}
public View onCreateView(LayoutInflater inflater,ViewGroup container,Bundle savedInstanceState)
{
View v =inflater.inflate(R.layout.feedback, null);
edname = (EditText)v.findViewById(R.id.editname);
edemail = (EditText)v.findViewById(R.id.editemail);
edcontact = (EditText)v.findViewById(R.id.editcontact);
edcomment = (EditText)v.findViewById(R.id.editcomment);
btnsend = (Button)v.findViewById(R.id.btnsend);
product = (Spinner)v.findViewById(R.id.editproduct);
textViewt2 = (TextView)v.findViewById(R.id.textViewt2);
t1 = (TextView)v.findViewById(R.id.textView1);
Bundle bung = this.getArguments();
if(bung!=null)
{
proid = bung.getInt("proid");
}
if(proid == 0)
{
Processtaluka pro = new Processtaluka();
pro.executeOnExecutor(pro.THREAD_POOL_EXECUTOR, new String[]{"selectdistict.php"});
}
else
{
Processtaluka pro = new Processtaluka();
pro.executeOnExecutor(pro.THREAD_POOL_EXECUTOR, new String[]{"selectsingledistict.php?proid="+proid});
}
t1.setOnClickListener(new OnClickListener()
{
#Override
public void onClick(View v) {
Intent callweb = new Intent(Intent.ACTION_VIEW);
callweb.setData(Uri.parse("http://pulleycoupling.com/"));
startActivity(callweb);
}
});
textViewt2.setOnClickListener(new OnClickListener()
{
#Override
public void onClick(View v) {
Intent callIntent = new Intent(Intent.ACTION_CALL);
callIntent.setData(Uri.parse("tel:9824155380"));
startActivity(callIntent);
}
});
btnsend.setOnClickListener(new OnClickListener()
{
#Override
public void onClick(View v)
{
na=edname.getText().toString();
con=edcontact.getText().toString();
email=edemail.getText().toString();
comm = edcomment.getText().toString();
if(na==null||na==""||na.length()<2)
{
edname.setError("Please Enter Name");
}
else if(con == null || con == "" || con.length()<10)
{
edcontact.setError("Please Enter Contact");
}
else if(email == null || email == "" || email.length()<4)
{
edemail.setError("Please Enter Email");
}
else if(comm == null || comm== "" || comm.length()<2)
{
edcomment.setError("Please Enter Comment");
}
else
{
ProcessInquiry pro = new ProcessInquiry();
pro.execute(new String[]{"insertfeedback.php"});
}
}
});
return v;
}
private class ProcessInquiry extends AsyncTask<String, Void, Boolean>
{
ProgressDialog dialog = new ProgressDialog(getActivity());
#Override
protected void onPreExecute()
{
dialog.setMessage("Please Wait Feedback send..");
dialog.show();
}
#Override
protected Boolean doInBackground(String... Url)
{
for(String Url1 : Url)
{
try
{
Jobj = new JsonHelper();
ArrayList<NameValuePair> pair = new ArrayList<NameValuePair>();
pair.add(new BasicNameValuePair("name", na));
pair.add(new BasicNameValuePair("contact", con));
pair.add(new BasicNameValuePair("email", email));
pair.add(new BasicNameValuePair("comment", comm));
pair.add(new BasicNameValuePair("product", city));
Jobj.MakeJsonCall(Url1, 2, pair);
Log.e("Url", Url1);
return true;
}
catch (Exception e)
{
return false;
}
}
return true;
}
#Override
protected void onPostExecute(Boolean result)
{
if(result==true)
{
Toast.makeText(getActivity(), "Feedback Send Sucessfully", 1000).show();
Intent i=new Intent(getActivity(),FragmentMaster.class);
i.putExtra("frgNo", "0");
startActivity(i);
edname.setText("");
edcomment.setText("");
edcontact.setText("");
edemail.setText("");
}
dialog.dismiss();
}
}
private class Processtaluka extends AsyncTask<String, Void, Boolean>
{
#Override
protected void onPreExecute()
{
}
#Override
protected Boolean doInBackground(String... Url)
{
for(String Url1 : Url)
{
Jobj = new JsonHelper();
obj = Jobj.MakeJsonCall(Url1, 2);
try
{
llistttt = new ArrayList<ProductModel>();
JSONArray JArr = obj.getJSONArray("record");
if(proid == 0)
{
}
else
{
}
for(int i=0;i<JArr.length();i++)
{
JSONObject dObj = JArr.getJSONObject(i);
llistttt.add(new ProductModel( dObj.getString("sub_id"), dObj.getString("sub_name")));
}
}
catch (JSONException e)
{
e.printStackTrace();
}
return true;
}
return true;
}
#Override
protected void onPostExecute(Boolean result)
{
madappppppppppp = new ProductAdapter(getActivity(),llistttt);
product.setAdapter(madappppppppppp);
product.setPrompt("Select The Service You Want");
product.setOnItemSelectedListener(new OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> arg0, View arg1,
int arg2, long arg3) {
city= llistttt.get(arg2).getSubname();
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
}
});
}
}
}

HTTP POST + ANDROID not giving response

I am beginner for Android. I want to send the data to my PHP page. but here i m trying to toast that post values. but there is no response. Plz help me.
My Code is:
public class send_msgActivity extends Activity{
//static final String KEY_NAME = "name";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.send_msg);
Button btn_ok = (Button) findViewById(R.id.btn_ok);
btn_ok.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
EditText editText1 = (EditText)findViewById(R.id.sender);
String S_name = editText1.getText().toString();
EditText editText2 = (EditText)findViewById(R.id.reciever);
String S_email = editText2.getText().toString();
postData(S_name,S_email);
}
});
};
public void postData(String name,String email) {
// Create a new HttpClient and Post Header
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://www.URL.com/yourpage.php");
try {
// Add your data
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
nameValuePairs.add(new BasicNameValuePair("Fname", name));
nameValuePairs.add(new BasicNameValuePair("Femail", email));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
// Execute HTTP Post Request
//HttpResponse response = httpclient.execute(httppost, new BasicResponseHandler());
HttpResponse response = httpclient.execute(httppost);
String reverseString = response.toString();
Toast.makeText(this, "response" + reverseString, Toast.LENGTH_LONG).show();
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
} catch (IOException e) {
// TODO Auto-generated catch block
}
}
}
Use this example how to code HTTPpost method
package com.example.login;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import org.apache.http.HttpResponse;a
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.os.AsyncTask;
import android.os.Bundle;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
public class pdf extends Activity
{
public boolean connect=false,logged=false;
public String db_select;
ListView l1;
String mPwd,UName1="Success",UName,ret;
public Iterator<String> itr;
private String SERVICE_URL = "http://61.12.7.197:8080/Agero/person/pdf";
private String SERVICE_URL1 = "http://61.12.7.197:8080/Agero/person/url";
//private final String SERVICE_URL = "http://10.1.1.138:8080/Agero/person/pdf";
//private final String SERVICE_URL1 = "http://10.1.1.138:8080/Agero/person/url";
private final String TAG = "Course";
ArrayList<String> todoItems;
Boolean isInternetPresent = false;
ConnectionDetector cd;
ArrayAdapter<String> aa;
public List<String> list1=new ArrayList<String>();
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.pdf);
l1 = (ListView)findViewById(R.id.list);
todoItems = new ArrayList<String>();
aa = new ArrayAdapter<String>(this,R.layout.list_row,R.id.title,todoItems);
l1.setAdapter(aa);
todoItems.clear();
cd = new ConnectionDetector(getApplicationContext());
isInternetPresent = cd.isConnectingToInternet();
if(isInternetPresent)
{
try
{
validat_user();
//display("hi");
}
catch(Exception e)
{
display("Network error.\nPlease check with your network settings.");
}
}
else
{
display("No Internet Connection..");
}
l1.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// TODO Auto-generated method stub
String name=(String)parent.getItemAtPosition(position);
/*Toast.makeText(getBaseContext(), name, Toast.LENGTH_LONG).show();
Intent i = new Intent(getBaseContext(),Webview.class);
i.putExtra("USERNAME", name);
startActivity(i);*/
cd = new ConnectionDetector(getApplicationContext());
isInternetPresent = cd.isConnectingToInternet();
if(isInternetPresent)
{
try
{
validat_user1(name);
}
catch(Exception e)
{
display("Network error.\nPlease check with your network settings.");
}
}
else
{
display("No Internet Connection..");
}
}
});
}
public void display(String msg)
{
Toast.makeText(pdf.this, msg, Toast.LENGTH_LONG).show();
}
private void validat_user()
{
WebServiceTask wst = new WebServiceTask(WebServiceTask.POST_TASK, this, "");
// wst.addNameValuePair("State", stg1);
// wst.addNameValuePair("Emp_PWD", stg2);
// db_select=stg1;
//display("I am");
wst.execute(new String[] { SERVICE_URL });
//display(SERVICE_URL);
}
private void validat_user1(String stg1)
{
db_select=stg1;
WebServiceTask wst = new WebServiceTask(WebServiceTask.POST_TASK, this, "Loading...");
wst.addNameValuePair1("PDF_NAME", stg1);
wst.execute(new String[] { SERVICE_URL1 });
}
#SuppressWarnings("deprecation")
public void no_net()
{
display( "No Network Connection");
final AlertDialog alertDialog = new AlertDialog.Builder(pdf.this).create();
alertDialog.setTitle("No Internet Connection");
alertDialog.setMessage("You don't have internet connection.\nElse please check the Internet Connection Settings.");
//alertDialog.setIcon(R.drawable.error_info);
alertDialog.setCancelable(false);
alertDialog.setButton("Close", new DialogInterface.OnClickListener()
{
public void onClick(DialogInterface dialog, int which)
{
alertDialog.cancel();
pdf.this.finish();
System.exit(0);
}
});
alertDialog.setButton2("Use Local DataBase", new DialogInterface.OnClickListener()
{
public void onClick(DialogInterface dialog, int which)
{
display( "Accessing local DataBase.....");
alertDialog.cancel();
}
});
alertDialog.show();
}
private class WebServiceTask extends AsyncTask<String, Integer, String> {
public static final int POST_TASK = 1;
private static final String TAG = "WebServiceTask";
// connection timeout, in milliseconds (waiting to connect)
private static final int CONN_TIMEOUT = 3000;
// socket timeout, in milliseconds (waiting for data)
private static final int SOCKET_TIMEOUT = 5000;
private int taskType = POST_TASK;
private Context mContext = null;
private String processMessage = "Processing...";
private ArrayList<NameValuePair> params = new ArrayList<NameValuePair>();
private ProgressDialog pDlg = null;
public WebServiceTask(int taskType, Context mContext, String processMessage) {
this.taskType = taskType;
this.mContext = mContext;
this.processMessage = processMessage;
}
public void addNameValuePair1(String name, String value) {
params.add(new BasicNameValuePair(name, value));
}
#SuppressWarnings("deprecation")
private void showProgressDialog() {
pDlg = new ProgressDialog(mContext);
pDlg.setMessage(processMessage);
pDlg.setProgressDrawable(mContext.getWallpaper());
pDlg.setProgressStyle(ProgressDialog.STYLE_SPINNER);
pDlg.setCancelable(false);
pDlg.show();
}
#Override
protected void onPreExecute() {
showProgressDialog();
}
protected String doInBackground(String... urls) {
String url = urls[0];
String result = "";
HttpResponse response = doResponse(url);
if (response == null) {
return result;
} else {
try {
result = inputStreamToString(response.getEntity().getContent());
} catch (IllegalStateException e) {
Log.e(TAG, e.getLocalizedMessage(), e);
} catch (IOException e) {
Log.e(TAG, e.getLocalizedMessage(), e);
}
}
return result;
}
#Override
protected void onPostExecute(String response) {
handleResponse(response);
pDlg.dismiss();
}
// Establish connection and socket (data retrieval) timeouts
private HttpParams getHttpParams() {
HttpParams htpp = new BasicHttpParams();
HttpConnectionParams.setConnectionTimeout(htpp, CONN_TIMEOUT);
HttpConnectionParams.setSoTimeout(htpp, SOCKET_TIMEOUT);
return htpp;
}
private HttpResponse doResponse(String url) {
// Use our connection and data timeouts as parameters for our
// DefaultHttpClient
HttpClient httpclient = new DefaultHttpClient(getHttpParams());
HttpResponse response = null;
try {
switch (taskType) {
case POST_TASK:
HttpPost httppost = new HttpPost(url);
// Add parameters
httppost.setEntity(new UrlEncodedFormEntity(params));
response = httpclient.execute(httppost);
break;
}
} catch (Exception e) {
display("Remote DataBase can not be connected.\nPlease check network connection.");
Log.e(TAG, e.getLocalizedMessage(), e);
return null;
}
return response;
}
private String inputStreamToString(InputStream is) {
String line = "";
StringBuilder total = new StringBuilder();
// Wrap a BufferedReader around the InputStream
BufferedReader rd = new BufferedReader(new InputStreamReader(is));
try {
// Read response until the end
while ((line = rd.readLine()) != null) {
total.append(line);
}
} catch (IOException e) {
Log.e(TAG, e.getLocalizedMessage(), e);
}
// Return full string
return total.toString();
}
}
public void handleResponse(String response)
{ //display("JSON responce is : "+response);
if(!response.equals(""))
{
try {
JSONObject jso = new JSONObject(response);
int UName = jso.getInt("status1");
if(UName==1)
{
String status = jso.getString("status");
ret=status.substring(13,status.length()-2);
todoItems.add(0, status);
aa.notifyDataSetChanged();
}
else if(UName==-1)
{
String status = jso.getString("status");
//display(status);
Intent intObj=new Intent(pdf.this,Webview.class);
intObj.putExtra("USERNAME", status);
startActivity(intObj);
}
else
{
// int count=Integer.parseInt(UName);
// display("Number of Projects have been handling in AFL right now: "+count);
list1=new ArrayList<String>();
JSONArray array=jso.getJSONArray("reps1");
for(int i=0;i<array.length();i++)
{
list1.add(array.getJSONObject(i).getString("pdfName"));
}
itr=list1.iterator();
while(itr.hasNext())
{
//str1=itr.next()+"\n";
todoItems.add(0, itr.next().toString());
aa.notifyDataSetChanged();
}
//tv1.setText(str1);
}
} catch (Exception e) {
Log.e(TAG, e.getLocalizedMessage(), e);
return;
}
}
else
{
display("unable to reach the server");
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.activity_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.home:
Intent intObj=new Intent(pdf.this, MainActivity.class);
intObj.putExtra("finish", true); // if you are checking for this in your other Activities
intObj.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP |
Intent.FLAG_ACTIVITY_CLEAR_TASK |
Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intObj);
//pdf.this.finish();
finish();
return (true);
}
return super.onOptionsItemSelected(item);
}
}

Categories

Resources