HTTP POST + ANDROID not giving response - android

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

Related

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

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

dialog box is not dismissing even the images completely loaded

Here is my code for fetching and loading some datas and images from mysql database in a loop,The problem is the dialog box "Loading image " is not dismissing even after the images completely loaded.
I'm new in android,Please anybody help me.
Java
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
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.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.Fragment;
import android.app.ProgressDialog;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;
public class News_events extends Fragment {
private String jsonResult;
private String url = "http://192.168.2.7/crescentnews/select.php";
HttpPost httppost;
StringBuffer buffer;
HttpResponse response;
HttpClient httpclient;
List<NameValuePair> nameValuePairs;
ProgressDialog dialog = null;
ImageView img;
Bitmap bitmap;
ProgressDialog pDialog;
InputStream is=null;
String result=null;
String line=null;
int code;
public News_events(){}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_news_events, container, false);
accessWebService();
return rootView;
}
// Async Task to access the web
private class JsonReadTask extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... params) {
List<NameValuePair> nameValuePair = new ArrayList<NameValuePair>(1);
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(params[0]);
try {
httppost.setEntity(new UrlEncodedFormEntity(nameValuePair));
HttpResponse response = httpclient.execute(httppost);
jsonResult = inputStreamToString(
response.getEntity().getContent()).toString();
}
catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
private StringBuilder inputStreamToString(InputStream is) {
String rLine = "";
StringBuilder answer = new StringBuilder();
BufferedReader rd = new BufferedReader(new InputStreamReader(is));
try {
while ((rLine = rd.readLine()) != null) {
answer.append(rLine);
}
}
catch (IOException e) {
// e.printStackTrace();
Toast.makeText(getActivity().getApplicationContext(),
"Error..." + e.toString(), Toast.LENGTH_LONG).show();
}
return answer;
}
#Override
protected void onPostExecute(String result) {
display();
}
}// end async task
public void accessWebService() {
JsonReadTask task = new JsonReadTask();
// passes values for the urls string array
task.execute(new String[] { url });
}
// build hash set for list view
public void display() {
try {
JSONObject jsonResponse = new JSONObject(jsonResult);
JSONArray jsonMainNode = jsonResponse.optJSONArray("news_details");
LinearLayout MainLL= (LinearLayout)getActivity().findViewById(R.id.newslayout);
//LinearLayout headLN=(LinearLayout)findViewById(R.id.headsection);
for (int i = 0; i < jsonMainNode.length(); i++) {
JSONObject jsonChildNode = jsonMainNode.getJSONObject(i);
final String head = jsonChildNode.optString("title");
final String details = jsonChildNode.optString("text");
final String date = jsonChildNode.optString("date");
final String image = jsonChildNode.optString("img");
//final String time = jsonChildNode.optString("time");
//img = new ImageView(this.getActivity());
//new LoadImage().execute("http://192.168.2.7/crescentnews/images/"+image);
img = new ImageView(this.getActivity());
LoadImage ldimg=new LoadImage();
ldimg.setImage(img);
ldimg.execute("http://192.168.2.7/crescentnews/images/"+image);
TextView headln = new TextView(this.getActivity());
headln.setText(head); // News Headlines
headln.setTextSize(20);
headln.setTextColor(Color.BLACK);
headln.setGravity(Gravity.CENTER);
headln.setBackgroundResource(R.drawable.menubg);
headln.setPadding(10, 20, 10, 0);
headln.setWidth(100);
headln.setClickable(true);
headln.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
//Toast.makeText(getBaseContext(), head, Toast.LENGTH_SHORT).show();
Intent intent = new Intent(getActivity().getApplicationContext(),MainActivity.class);
intent.putExtra("head",head.toString());
intent.putExtra("details",details.toString());
intent.putExtra("date",date.toString());
// intent.putExtra("time",time.toString());
startActivity(intent);
}
});
ImageView photo=new ImageView(this.getActivity());
//dateln.setBackgroundColor(Color.parseColor("#f20056"));
photo.setBackgroundColor(Color.parseColor("#000000"));
photo.setPadding(0, 0, 10, 10);
photo.setClickable(true);
// Drawable drawable = LoadImageFromWebOperations("http://192.168.2.7/crescentnews/images/"+pic);
// userpic.setImageDrawable(drawable);
TextView dateln = new TextView(this.getActivity());
dateln.setText(date); // News Headlines
dateln.setTextSize(12);
dateln.setTextColor(Color.BLACK);
dateln.setGravity(Gravity.RIGHT);
//dateln.setBackgroundColor(Color.parseColor("#f20056"));
dateln.setBackgroundColor(0x00000000);
dateln.setPadding(0, 0, 10, 10);
dateln.setWidth(100);
dateln.setClickable(true);
dateln.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent intent = new Intent(getActivity().getApplicationContext(), MainActivity.class);
intent.putExtra("head",head.toString());
intent.putExtra("details",details.toString());
intent.putExtra("date",date.toString());
// intent.putExtra("time",time.toString());
startActivity(intent);
}
});
View sep=new View(this.getActivity());
sep.setBackgroundColor(Color.parseColor("#252525"));
sep.setMinimumHeight(10);
TextView detailsln = new TextView(this.getActivity());
detailsln.setText(details); // News Details
detailsln.setTextSize(12);
detailsln.setTextColor(Color.BLACK);
detailsln.setGravity(Gravity.LEFT);
detailsln.setPadding(10, 10, 10, 10);
MainLL.addView(headln);
MainLL.addView(dateln);
MainLL.addView(photo);
MainLL.addView(img);
MainLL.addView(detailsln);
MainLL.addView(sep);
detailsln.setClickable(true);
detailsln.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent intent = new Intent(getActivity().getApplicationContext(), MainActivity.class);
intent.putExtra("head",head.toString());
intent.putExtra("details",details.toString());
intent.putExtra("date",date.toString());
// intent.putExtra("time",time.toString());
startActivity(intent);
}
});
}
} catch (JSONException e) {
Toast.makeText(getActivity().getApplicationContext(), "Error" + e.toString(),
Toast.LENGTH_SHORT).show();
}
}
private class LoadImage extends AsyncTask<String, String, Bitmap> {
ImageView img;
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(getActivity());
pDialog.setMessage("Loading Image ....");
pDialog.show();
}
public void setImage(ImageView img ){
this.img=img;
}
protected Bitmap doInBackground(String... args) {
try {
bitmap = BitmapFactory.decodeStream((InputStream)new URL(args[0]).openStream());
} catch (Exception e) {
e.printStackTrace();
}
return bitmap;
}
protected void onPostExecute(Bitmap image) {
if(image != null){
img.setImageBitmap(image);
}
pDialog.dismiss();
}
}
}

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

Make a string from a View element

I have two seekbars in my main activity but I can only use one of them at a time, so I need to retrieve a value seekbarx and seekbary, store either of them in a string variable to use it forward. I already used onProgressChange and onStopTrackingTouch but I guess it doesn't hold the value long enough.
This is what I had for the seekbars
package edu.itdurango.servocontrolyun;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.atomic.AtomicBoolean;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONObject;
import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.widget.SeekBar;
import android.widget.TextView;
import android.widget.SeekBar.OnSeekBarChangeListener;
public class MainActivity extends Activity {
// TODO: adjust ARDUINO_IP_ADDRESS
public final String ARDUINO_IP_ADDRESS = "192.168.1.71"; //Dirección IP del Arduino Yun
public final String TAG = "ArduinoYun";
public String servo;
private SeekBar SeekBarX; //Barra de búsqueda del eje X
private SeekBar SeekBarY; //Barra de búsqueda del eje Y
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
SeekBarX = (SeekBar) findViewById(R.id.barraEjeX);
/*SeekBarX.setOnClickListener(new View.OnClickListener() {
public void onClick(View barraEjeX) {
servo = "servox/";
}
});*/
SeekBarX.setOnSeekBarChangeListener(new OnSeekBarChangeListener() {
#Override
public void onStopTrackingTouch(SeekBar barraEjeX) {
}
#Override
public void onStartTrackingTouch(SeekBar barraEjeX) {
}
#Override
public void onProgressChanged(SeekBar barraEjeX, int progressX,
boolean fromUser) {
servo = "servox/";
log("touching X bar. servo = " + servo);
QueueX.offer(progressX);
}
});
SeekBarY = (SeekBar) findViewById(R.id.barraEjeY);
/*SeekBarY.setOnClickListener(new View.OnClickListener() {
public void onClick(View barraEjeY) {
servo = "servoy/";
}
});*/
SeekBarY.setOnSeekBarChangeListener(new OnSeekBarChangeListener() {
#Override
public void onStopTrackingTouch(SeekBar barraEjeY) {
}
#Override
public void onStartTrackingTouch(SeekBar barraEjeY) {
}
#Override
public void onProgressChanged(SeekBar barraEjeY, int progressY,
boolean fromUser) {
servo = "servoy/";
log("touching Y bar. servo = " + servo);
QueueY.offer(progressY);
}
});
}
#Override
protected void onStart() {
mStop.set(false);
if(sNetworkThreadSend == null){
sNetworkThreadSend = new Thread(mNetworkRunnableSend);
sNetworkThreadSend.start();
}
super.onStart();
}
#Override
protected void onStop() {
mStop.set(true);
QueueX.clear();
QueueX.offer(-1);
QueueY.clear();
QueueY.offer(-1);
if(sNetworkThreadSend != null) sNetworkThreadSend.interrupt();
super.onStop();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
public void log(String s){
Log.d(">==< "+TAG+" >==<", s);
}
private ArrayBlockingQueue<Integer> QueueX = new ArrayBlockingQueue<Integer>(100);
private ArrayBlockingQueue<Integer> QueueY = new ArrayBlockingQueue<Integer>(100);
private AtomicBoolean mStop = new AtomicBoolean(false);
private static Thread sNetworkThreadSend = null;
private final Runnable mNetworkRunnableSend = new Runnable() {
#Override
public void run() {
log("starting network thread for sending");
String urlBase = "http://"+ARDUINO_IP_ADDRESS+"/arduino/"+servo;
String url;
try {
while(!mStop.get()){
int val;
if (servo == "servoy/"){
val = QueueY.take();
if(val >= 0){
HttpClient httpClient = new DefaultHttpClient();
url = urlBase.concat(String.valueOf(val));
log("executing httpClient request");
HttpResponse response = httpClient.execute(new HttpGet(url));
log(url);
}
}
if (servo == "servox/"){
val = QueueX.take();
if(val >= 0){
HttpClient httpClient = new DefaultHttpClient();
url = urlBase.concat(String.valueOf(val));
log("executing httpClient request");
HttpResponse response = httpClient.execute(new HttpGet(url));
log(url);
}
}
}
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
}
log("returning from network thread for sending");
sNetworkThreadSend = null;
}
};
private static Thread sNetworkThreadReceive = null;
private final Runnable mNetworkRunnableReceive = new Runnable() {
#Override
public void run() {
log("starting network thread for receiving");
String url = "http://"+ARDUINO_IP_ADDRESS+"/data/get/D9";
while(!mStop.get()){
try {
String string = readURL(url);
String value = "";
try {
JSONObject jsonMain = new JSONObject(string);
value = jsonMain.get("value").toString();
log("value = "+value);
} catch (Exception e) {
e.printStackTrace();
}
updateText(value);
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
log("returning from network thread for receiving");
sNetworkThreadReceive = null;
}
};
public void updateText(final String value){
runOnUiThread(new Runnable() {
#Override
public void run() {
TextView textView = (TextView) findViewById(R.id.textView1);
textView.setText(value);
}
});
}
public String readURL(String value){
URL url;
StringBuilder builder = new StringBuilder();
try {
url = new URL(value);
URLConnection yc = url.openConnection();
BufferedReader in = new BufferedReader(new InputStreamReader(yc.getInputStream()));
String inputLine;
while ((inputLine = in.readLine()) != null){
builder.append(inputLine);
}
in.close();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return builder.toString();
}
}
It prints in the LogCat touching Y bar. servo = servoy/ but when I want to use the servo value it prints null.
How can I hold the value for this string?

progress dialog keeps on displaying

I have written a long code in android and which displays a progress dialog when the restaurant list is loaded into the listview. Now the problem is that its working fine when restaurant list is loaded again on users filter changes but only at the first time. it just keeps on displaying even if the listview is populated and user has to manually dismiss it pressing the back button of deivce. I dont knw where to write pg.dismiss() in this case. Posting my code here . plz advise me..
package com.Refinedymapps;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.StringReader;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.location.Geocoder;
import android.location.LocationManager;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.ImageButton;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
public class Restaurantlist extends Activity implements OnClickListener, OnItemSelectedListener {
ProgressDialog pg;
private ImageButton imgbtn;
private ListView restaurant;
private TextView city;
String sendid,flagdopost="",linkurl;
LocationManager locationManger;
Geocoder gc;
Bundle bundle;
private int j=0;
private Spinner cuisine,area;
static ArrayList<HashMap<String,String>> customlist= new ArrayList<HashMap<String,String>>();
private String asynctaskflag="",cuisineval,areaval;
List<String> tempareanamelist,tempcuisinenamelist,areanamelist,cuisinelist,cuisineidlist,restaurantnames,areanames,restaurantidlist,originalcuisinelist,originalarealist;
String str,coun,stat,cid,sid,cityid,cityname;
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.restaurantlisting);
linkurl=getResources().getString(R.string.linkurl);
city=(TextView)findViewById(R.id.textviewcity);
cuisine=(Spinner)findViewById(R.id.spncuisine);
area=(Spinner)findViewById(R.id.spnarea);
restaurant=(ListView)findViewById(R.id.lstrestaurant);
imgbtn=(ImageButton)findViewById(R.id.imageButton1);
bundle = this.getIntent().getExtras();
imgbtn.setImageResource(R.drawable.searchloc);
asynctaskflag="init";
new Thetask().execute(asynctaskflag,null,null);
imgbtn.setOnClickListener(new OnClickListener(){
public void onClick(View arg0) {
Intent newlocintent=new Intent(Restaurantlist.this,Restaurantlistdisplay.class);
startActivity(newlocintent);
}
});
restaurant.setOnItemClickListener(new OnItemClickListener(){
public void onItemClick(AdapterView<?> arg0, View arg1,
int arg2, long arg3) {
Toast.makeText(getBaseContext(), "resname"+restaurantnames.get(arg2)+"areaname"+areanames.get(arg2), 10).show();
String[] getid={"itemclick",restaurantnames.get(arg2),areanames.get(arg2)};
new Thetask().execute(getid);
}
});
}
public void populateReslist()
{
Log.i("inside populatereslist","value of j is:"+j);
for(int i=0;i<restaurantnames.size();i++)
{
HashMap<String,String> temp = new HashMap<String,String>();
temp.put("Restaurant Name",restaurantnames.get(i).toString());
temp.put("Area Name", areanames.get(i).toString());
customlist.add(temp);
}
}
public List<String> getAreanames(String cityid)
{
String list = null;
areanamelist=new ArrayList<String>();
final HttpClient client=new DefaultHttpClient();
final HttpGet req=new HttpGet(linkurl+"/ymaws/resources/restaurant/"+cityid+"/areas/");
HttpResponse httpResponse;
try {
httpResponse=client.execute(req);
HttpEntity entity = httpResponse.getEntity();
Log.i("entity", entity.toString());
if (entity != null)
{
InputStream instream = entity.getContent();
BufferedReader reader = new BufferedReader(new InputStreamReader(instream));
StringBuilder sb = new StringBuilder();
String line = null;
try
{
while ((line = reader.readLine()) != null)
{
sb.append(line + "\n");
}
}
catch (IOException e)
{
e.printStackTrace();
}
finally
{
try
{
instream.close();
}
catch (IOException e)
{
e.printStackTrace();
}
}
// Closing the input stream will trigger connection release
list= sb.toString();
Log.i("areaname xml is", list.toString());
}
}
catch(Exception e)
{
}
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
factory.setNamespaceAware(true);
try
{
DocumentBuilder builder = factory.newDocumentBuilder();
Document dom = builder.parse(new InputSource(new StringReader(list)));
Element root = dom.getDocumentElement();
NodeList items = root.getElementsByTagName("Area");
for (int i=0;i<items.getLength();i++)
{
Node item = items.item(i);
NodeList properties = item.getChildNodes();
for (int j=0;j<properties.getLength();j++)
{
Node property = properties.item(j);
String name = property.getNodeName();
if (name.equalsIgnoreCase("areaName"))
{
areanamelist.add(property.getFirstChild().getNodeValue());
}
else
{
}
}
}
//Log.i("areaname list in getAreas method", areanamelist.toString());
return areanamelist;
}
catch (Exception e)
{
throw new RuntimeException(e);
}
}
public List<String> getCuisines(String cityid)
{
String list = null;
cuisinelist=new ArrayList<String>();
cuisineidlist=new ArrayList<String>();
final HttpClient client=new DefaultHttpClient();
final HttpGet req=new HttpGet(linkurl+"/ymaws/resources/restaurant/"+cityid+"/cuisines/");
HttpResponse httpResponse;
try {
httpResponse=client.execute(req);
HttpEntity entity = httpResponse.getEntity();
Log.i("entity", entity.toString());
if (entity != null)
{
InputStream instream = entity.getContent();
BufferedReader reader = new BufferedReader(new InputStreamReader(instream));
StringBuilder sb = new StringBuilder();
String line = null;
try
{
while ((line = reader.readLine()) != null)
{
sb.append(line + "\n");
}
}
catch (IOException e)
{
e.printStackTrace();
}
finally
{
try
{
instream.close();
}
catch (IOException e)
{
e.printStackTrace();
}
}
// Closing the input stream will trigger connection release
list= sb.toString();
Log.i("cuisinename xml is", list.toString());
}
}
catch(Exception e)
{
}
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
factory.setNamespaceAware(true);
try
{
DocumentBuilder builder = factory.newDocumentBuilder();
Document dom = builder.parse(new InputSource(new StringReader(list)));
Element root = dom.getDocumentElement();
NodeList items = root.getElementsByTagName("Cuisine");
for (int i=0;i<items.getLength();i++)
{
Node item = items.item(i);
NodeList properties = item.getChildNodes();
for (int j=0;j<properties.getLength();j++)
{
Node property = properties.item(j);
String name = property.getNodeName();
if (name.equalsIgnoreCase("cuisineName"))
{
cuisinelist.add(property.getFirstChild().getNodeValue());
}
else if(name.equalsIgnoreCase("cuisineId"))
{
cuisineidlist.add(property.getFirstChild().getNodeValue());
}
}
}
Log.i("getcuisine cuisinelist",cuisinelist.toString());
return cuisinelist;
}
catch (Exception e)
{
throw new RuntimeException(e);
}
}
public void firequery()
{
String url = null;
if(cuisineval=="*" && areaval=="*")
{
url=linkurl+"/ymaws/resources/restaurant/"+cityid+"/restaurants";
}
else if(cuisineval!="*" && areaval=="*")
{
for(int i=0;i<originalcuisinelist.size();i++)
{
Log.i("cuisinelist original item is",""+originalcuisinelist.get(i));
Log.i("cuisineidlist is",cuisineidlist.toString());
if((cuisine.getSelectedItem().toString()).equalsIgnoreCase(originalcuisinelist.get(i).toString()))
{
Log.i("cuisineid selected is",""+cuisineidlist.get(i));
url=linkurl+"/ymaws/resources/restaurant?cityid="+cityid+"&cuisineid="+cuisineidlist.get(i);
}
}
}
else if(cuisineval=="*" && areaval!="*")
{
url = linkurl+"/ymaws/resources/restaurant?cityid="+cityid+"&areanm="+area.getSelectedItem().toString();
}
else
{
for(int i=0;i<originalcuisinelist.size();i++)
{
if((cuisine.getSelectedItem().toString()).equalsIgnoreCase(originalcuisinelist.get(i).toString()))
{
url=linkurl+"/ymaws/resources/restaurant?cityid="+cityid+"&cuisineid="+cuisineidlist.get(i)+"&areanm="+area.getSelectedItem().toString();
}
}
}
getResult(url);
}
public void getResult(String url)
{
String list = null;
restaurantnames=new ArrayList<String> ();
areanames=new ArrayList<String>();
restaurantidlist=new ArrayList<String>();
final HttpClient client=new DefaultHttpClient();
Log.i("url is","url:"+url.toString());
final HttpGet req=new HttpGet(url.replaceAll(" ", "%20"));
HttpResponse httpResponse;
try {
httpResponse=client.execute(req);
HttpEntity entity = httpResponse.getEntity();
Log.i("entity", entity.toString());
if (entity != null)
{
InputStream instream = entity.getContent();
BufferedReader reader = new BufferedReader(new InputStreamReader(instream));
StringBuilder sb = new StringBuilder();
String line = null;
try
{
while ((line = reader.readLine()) != null)
{
sb.append(line + "\n");
}
}
catch (IOException e)
{
e.printStackTrace();
}
finally
{
try
{
instream.close();
}
catch (IOException e)
{
e.printStackTrace();
}
}
list= sb.toString();
Log.i("list xml is", list.toString());
}
}
catch(Exception e)
{
}
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
factory.setNamespaceAware(true);
try
{
if(list!=null)
{
DocumentBuilder builder = factory.newDocumentBuilder();
Document dom = builder.parse(new InputSource(new StringReader(list)));
Element root = dom.getDocumentElement();
NodeList items = root.getElementsByTagName("resLovData");
for (int i=0;i<items.getLength();i++)
{
Node item = items.item(i);
NodeList properties = item.getChildNodes();
for (int j=0;j<properties.getLength();j++)
{
Node property = properties.item(j);
String name = property.getNodeName();
if (name.equalsIgnoreCase("locName"))
{
restaurantnames.add(property.getFirstChild().getNodeValue());
}
else if(name.equalsIgnoreCase("areaName"))
{
areanames.add(property.getFirstChild().getNodeValue());
}
else if(name.equalsIgnoreCase("locId"))
{
restaurantidlist.add(property.getFirstChild().getNodeValue());
}
}
}
}
else
{
}
}
catch (Exception e)
{
throw new RuntimeException(e);
}
}
public void onClick(View arg0) {
// TODO Auto-generated method stub
}
public class Thetask extends AsyncTask<String, Void, Void>
{
String x,y;
#Override
public void onPreExecute()
{
pg =new ProgressDialog(Restaurantlist.this);
pg.setMessage("fetching info....");
pg.setIndeterminate(true);
pg.setCancelable(true);
Log.i("inside preexecute","in pre execute");
pg.show();
}
public Void doInBackground(String... params)
{
if(params[0].equalsIgnoreCase("init"))
{
Log.i("inside doinbackground 1st",flagdopost);
cid=bundle.getString("cid");
sid=bundle.getString("sid");
cityid=bundle.getString("cityid");
cityname=bundle.getString("cityname");
originalcuisinelist=new ArrayList<String>();
originalcuisinelist=getCuisines(cityid);
tempcuisinenamelist = getCuisines(cityid);
tempcuisinenamelist.add(0,"All");
originalarealist=new ArrayList<String>();
originalarealist=getAreanames(cityid);
tempareanamelist=getAreanames(cityid);
tempareanamelist.add(0,"All");
Log.i("area are",tempareanamelist.toString());
flagdopost="init";
Log.i("inside doinbackground 1st",flagdopost);
}
else if(params[0].equalsIgnoreCase(""))
{
flagdopost="";
j++;
if(j!=1)
{
firequery();
flagdopost="itemselected";
Log.i("inside doinbackground 2nd",flagdopost);
}
}
else if(params[0].equalsIgnoreCase("itemclick"))
{
x=params[1];
y=params[2];
for(int i=0;i<restaurantidlist.size();i++)
{
if((params[1].toString()).equalsIgnoreCase(restaurantnames.get(i)))
{
sendid=restaurantidlist.get(i);
}
}
Log.i("in do in backgroung idforbundle is", sendid);
flagdopost="itemclicked";
}
return null;
}
public void onPostExecute(Void result)
{
if(flagdopost.equalsIgnoreCase("init"))
{
city.setText(cityname);
ArrayAdapter<String> adaptercuisine=new ArrayAdapter<String>(Restaurantlist.this,android.R.layout.simple_spinner_item,tempcuisinenamelist);
adaptercuisine.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
ArrayAdapter<String> adapterarea=new ArrayAdapter<String>(Restaurantlist.this,android.R.layout.simple_spinner_item,tempareanamelist);
adapterarea.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
area.setAdapter(adapterarea);
area.setSelection(0);
cuisine.setAdapter(adaptercuisine);
cuisine.setSelection(0);
area.setOnItemSelectedListener(Restaurantlist.this);
cuisine.setOnItemSelectedListener(Restaurantlist.this);
}
else if(flagdopost.equalsIgnoreCase("itemselected"))
{
customlist.clear();
populateReslist();
restaurant.invalidateViews();
restaurant.setAdapter(new SimpleAdapter(Restaurantlist.this,customlist,R.layout.customlistrow,new String[] {"Restaurant Name","Area Name"},
new int[] {R.id.tvresname,R.id.tvareaname})
{
#Override
public View getView(int position, View convertView,ViewGroup parent)
{
View view =super.getView(position, convertView, parent);
return view;
}
});
}
else if(flagdopost.equalsIgnoreCase("itemclicked"))
{
Bundle bundle=new Bundle();
bundle.putString("locid",sendid);
Toast.makeText(getBaseContext(), "locId in dopost new one"+sendid, 10).show();
Intent resdetail = new Intent(Restaurantlist.this,Restaurantdetail.class);
resdetail.putExtras(bundle);
startActivity(resdetail);
}
pg.dismiss();
}
}
public void onItemSelected(AdapterView<?> arg0, View arg1, int arg2,
long arg3)
{
switch(arg0.getId())
{
case R.id.spncuisine:
asynctaskflag="";
if(cuisine.getSelectedItem().toString()!="All")
{
cuisineval=cuisine.getSelectedItem().toString();
}
else
{
cuisineval="*";
}
new Thetask().execute(asynctaskflag,null,null);
break;
case R.id.spnarea:
asynctaskflag="";
if(area.getSelectedItem().toString()!="All")
{
areaval=area.getSelectedItem().toString();
}
else
{
areaval="*";
}
new Thetask().execute(asynctaskflag,null,null);
break;
}
}
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
}
Try declaring your ProgressDialog inside the AsyncTask. Instead of as a Activity member variable.
public class Thetask extends AsyncTask<String, Void, Void>
{
ProgressDialog pg = null;
String x,y;
#Override
public void onPreExecute()
...

Categories

Resources