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();
}
}
Related
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);
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;
}
}
}
Hello i think i have done right thing but don't know where i am lagging.Here is my code in which i am starting a service from main activity but service is not started.If anyone know please help me.
MainActivity
package com.example.lalit.gcmtest;
import android.app.ProgressDialog;
import android.content.BroadcastReceiver;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONObject;
import android.widget.ImageView;
import android.widget.Toast;
import java.util.ArrayList;
import java.util.List;
public class MainActivity extends AppCompatActivity {
JsonParser jsonParser = new JsonParser();
String str;
private static final String TAG_SUCCESS = "success";
public static final String NOTIFICATION_URL = "http://kushjalwa.netau.net/tokenStore.php";
public static final String TOKEN_URL = "http://kushjalwa.netau.net/Token_Registration.php";
private static final int PLAY_SERVICES_RESOLUTION_REQUEST = 9000;
private static final String TAG = "MainActivity";
private BroadcastReceiver mRegistrationBroadcastReceiver;
//public ProgressDialog progress;
ProgressDialog pDialog;
static boolean flag=true;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if (flag) {
Intent intent = new Intent(this, MyRegistrationIntentService.class);
startService(intent);
flag=false;
}
else {
Intent i=getIntent();
str=i.getStringExtra("token");
Log.d("Token in Activity",str);
Log.d("CheckPoint", "check");
new SendingNotification().execute();
}
}
public class SendingNotification extends AsyncTask<String, String, String> {
int success;
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(MainActivity.this);
pDialog.setMessage("......Registering.......");
pDialog.setIndeterminate(false);
pDialog.setCancelable(false);
pDialog.show();
}
#Override
protected String doInBackground(String... args)
{
try {
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("token", str));
Log.d("request!", "heloo");
JSONObject json = jsonParser.makeHttpRequest(TOKEN_URL, "POST", params);
Log.d("Login attempt", json.toString());
success = json.getInt(TAG_SUCCESS);
if (success == 1)
{
Log.d("Login Successful!", json.toString());
}
else
{
Log.d("Sendind Fail", "Fail");
}
}
catch (Exception ex)
{
ex.printStackTrace();
}
return null;
}
protected void onPostExecute(String file_url)
{
pDialog.dismiss();
Toast.makeText(getApplicationContext(), "Token Stored", Toast.LENGTH_SHORT).show();
}
}
}
Service
package com.example.lalit.gcmtest;
import android.app.IntentService;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.AsyncTask;
import android.preference.PreferenceManager;
import android.util.Log;
import com.google.android.gms.gcm.GoogleCloudMessaging;
import com.google.android.gms.iid.InstanceID;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.List;
public class MyRegistrationIntentService extends IntentService {
public static String token = null;
private static final String TAG_SUCCESS = "success";
private static final String TAG = "RegIntentService";
public static final String TOKEN_URL = "http://kushjalwa.netau.net/Token_Registration.php";
public static final String NOTIFICATION_URL = "http://kushjalwa.netau.net/ceo.php";
private static final String[] TOPICS = {"global"};
public ProgressDialog pDialog;
Context context;
JsonParser jsonParser = new JsonParser();
public MyRegistrationIntentService() {
super(TAG);
}
#Override
protected void onHandleIntent(Intent intent) {
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
try {
synchronized (TAG) {
InstanceID instanceID = InstanceID.getInstance(this);
token = instanceID.getToken("879100952974",
GoogleCloudMessaging.INSTANCE_ID_SCOPE, null);
// [END get_token]
Log.i(TAG, "GCM Registration Token: " + token);
Intent dialogIntent = new Intent(this, MainActivity.class);
dialogIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
dialogIntent.putExtra("token",token);
startActivity(dialogIntent);
sharedPreferences.edit().putBoolean(QuickstartPreferences.SENT_TOKEN_TO_SERVER, true).apply();
// [END register_for_gcm]
}
} catch (Exception e) {
Log.d(TAG, "Failed to complete token refresh", e);
sharedPreferences.edit().putBoolean(QuickstartPreferences.SENT_TOKEN_TO_SERVER, false).apply();
}
Intent registrationComplete = new Intent(QuickstartPreferences.REGISTRATION_COMPLETE);
}
public class SendingToken extends AsyncTask<String, String, String> {
int success;
/* private ProgressDialog progressDialog = new ProgressDialog(getApplicationContext());
InputStream inputStream = null;
String result = "";
*/
protected void onPreExecute() {
/* progressDialog.setMessage("Your progress dialog message...");
progressDialog.show();
progressDialog.setOnCancelListener(new DialogInterface.OnCancelListener() {
public void onCancel(DialogInterface arg0) {
//MyAsyncTask.this.cancel(true);
}
});*/
}
#Override
protected String doInBackground(String... args) {
try {
// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("token", token));
Log.d("request!", "starting");
// getting product details by making HTTP request
JSONObject json = jsonParser.makeHttpRequest(TOKEN_URL, "POST", params);
Log.d("Login attempt", json.toString());
// json success tag
success = json.getInt(TAG_SUCCESS);
if (success == 1) {
Log.d("Login Successful!", json.toString());
} else {
Log.d("Sendind Fail", "Fail");
}
} catch (Exception ex) {
}
// [END subscribe_topics]
return null;
//}
}
#Override
protected void onPostExecute(String s) {
// pDialog.dismiss();
}
}
}
By Declaring the service in manifest all working fine.
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();
}
}
}
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);
}
}