httpclient does not work in asynctask - android

i am using httpclient in asynctask doInBackground for get my php-session value
this is my Java codes:
package com.example.example;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.Activity;
import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.os.Bundle;
public class MainActivity extends Activity {
private String aktuell_date_u,set_check;
public static DefaultHttpClient client = new DefaultHttpClient();
private ProgressDialog pd;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.login_main);
pd = new ProgressDialog(MainActivity.this);
pd.setMessage("bitte warten...");
pd.show();
new get_sessions();
}
private class get_sessions extends AsyncTask<String, Void, JSONObject> {
#Override
protected JSONObject doInBackground(String... arg0) {
HttpGet post = new HttpGet("http://www.example.com/getsessions.php");
try {
HttpResponse response = client.execute(post);
BufferedReader rd = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
StringBuilder sb = new StringBuilder();
String line = "";
while ((line = rd.readLine()) != null) {
sb.append(line);
break;
}
return new JSONObject(sb.toString());
} catch (JSONException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
protected void onPostExecute(JSONObject result){
aktuell_date_u = result.optString("aktuell_date_u").toString();
set_check = result.optString("set_check").toString();
pd.cancel();
}
}
}
and this is my php codes:
<?php
session_start();
header('content-type: aplication/json; charset=utf-8');
setcookie("cookie_test", date('U'));
$aktuell_date_u=date('U');
$_SESSION['set_check']=md5($aktuell_date_u);
echo '{"aktuell_date_u":"'.$aktuell_date_u.'","set_check":"'.$_SESSION['set_check'].'"}';
?>
the PregressDialog loads and loads ...
what i'm doing wrong, because my httpclient codes work out of doInBackground
Special thanks

You're not calling the AsyncTask's execute() method, so the AsyncTask never runs. Instead of
new get_sessions();
You need to call:
new get_sessions().execute(null);
As you're not using the arguments passed to doInBackground(), I'm not sure why you've defined them as String.
You should probably also look at some basic training on Java coding conventions and follow them - things like making Class names begin with an uppercase letter and camel casing them rather than using underscores. Following conventions makes your code easier for other people to read.

Related

get JSON Array from local server in android 6.0 with HttpURLConnection

I am trying to get a JSON Array from this local server for five days:
localhost/match_picture/service.php?action=read
and i can't do it !!
I search it in google and read too many documentations !
here is my code:
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
public class WebService {
public static String readUrl(String server_url) {
BufferedReader bufferedReader = null;
try {
URL url = new URL(server_url);
HttpURLConnection con = (HttpURLConnection) url.openConnection();
StringBuilder sb = new StringBuilder();
bufferedReader = new BufferedReader(new InputStreamReader(con.getInputStream()));
String json;
while ((json = bufferedReader.readLine()) != null) {
sb.append(json+"\n");
}
return sb.toString();
}catch (Exception e) {
e.printStackTrace();
}
return null;
}
}
and it's Main_Activity:
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.Toast;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
public class Activity_main extends AppCompatActivity {
private ArrayList<StructAcount> netAcount = new ArrayList<StructAcount>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
String result= WebService.readUrl("http://localhast/match_picture/service.php?action=read");
if (result != null) {
try {
JSONArray tasks = new JSONArray(result);
for (int i=0; i<tasks.length(); i++) {
StructAcount acount= new StructAcount();
JSONObject object = tasks.getJSONObject(i);
acount.id = object.getLong("user_id");
acount.name = object.getString("user_name");
acount.email = object.getString("user_email");
netAcount.add(acount);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
for (StructAcount acount: netAcount) {
Toast.makeText(Activity_main.this, "username: " + acount.name + "\n" + "useremail: " + acount.email , Toast.LENGTH_SHORT).show();
}
}
}
it is runing on emulator and crashes in this line:
bufferedReader = new BufferedReader(new InputStreamReader(con.getInputStream()));
and i dont know why ...
I am Searching for five days!!!!
I can do it with HttpClient
but i want to be update
I saw a vidoe in youtube that create a class in Main_Activity extends AsyncTask and make connenction in doInBackground(String... params). I try that and that works correcly. but because I want to do it in anoder class (WebService) and I dont know how can i sent result to Main_Activity , I remove that class extended from AsyncTask.
thank's for your help
sorry for my poor english
You have a NetworkOnMainThreadException to begin with.
And your app crashes.
Google how to solve it.

consuming rest web service in android

I'am following this tutorial for calling a web service in android & it works great, http://androidexample.com/Restful_Webservice_Call_And_Get_And_Parse_JSON_Data-_Android_Example/index.php?view=article_discription&aid=101
yet when i try to call another webservice using this code, just replacing the serverURL, the app gets blocked in th pre-execute(), can anyone tell me what else should I change ? I thought there was a common code for all web services ?
mainActivity.java
import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import org.apache.http.client.HttpClient;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.UnsupportedEncodingException;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button GetData = (Button) findViewById(R.id.GetServerData);
GetData.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// WebServer Request URL
String serverURL = "http://androidexample.com/media/webservice/JsonReturn.php";
// String serverURL = "http://hmkcode.appspot.com/rest/controller/get.json";
// String serverURL="http://gdata.youtube.com/feeds/api/videos?q=Android&v=2&max-results=20&alt=jsonc&hl=en";
// Use AsyncTask execute Method To Prevent ANR Problem
new LongOperation().execute(serverURL);
}
}
);
}
class LongOperation extends AsyncTask<String, Void, Void> {
private final HttpClient Client = new DefaultHttpClient();
private String Content;
private String Error = null;
private ProgressDialog Dialog = new ProgressDialog(MainActivity.this);
String data = "";
TextView uiUpdate = (TextView) findViewById(R.id.output);
TextView jsonParsed = (TextView) findViewById(R.id.jsonParsed);
protected void onPreExecute() {
// NOTE: You can call UI Element here.
//Start Progress Dialog (Message)
Dialog.setMessage("Please wait..");
Dialog.show();
}
// Call after onPreExecute method
protected Void doInBackground(String... urls) {
/************ Make Post Call To Web Server *********/
BufferedReader reader=null;
// Send data
try
{
// Defined URL where to send data
URL url = new URL(urls[0]);
// Send POST data request
URLConnection conn = url.openConnection();
conn.setDoOutput(true);
OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());
wr.write( data );
wr.flush();
// Get the server response
reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
StringBuilder sb = new StringBuilder();
String line = null;
// Read Server Response
while((line = reader.readLine()) != null)
{
// Append server response in string
sb.append(line + " ");
}
// Append Server Response To Content String
Content = sb.toString();
}
catch(Exception ex)
{
Error = ex.getMessage();
}
finally
{
try
{
reader.close();
}
catch(Exception ex) {}
}
/*****************************************************/
return null;
}
protected void onPostExecute(Void unused) {
// NOTE: You can call UI Element here.
// Close progress dialog
Dialog.dismiss();
if (Error != null) {
uiUpdate.setText("Output : " + Error);
} else {
// Show Response Json On Screen (activity)
uiUpdate.setText(Content);
//String OutputData = MainActivity.parse(Content);
//Show Parsed Output on screen (activity)
//jsonParsed.setText(OutputData);
}
}
}
}
I changed send PostRequest with this code: //SEND Get data reques HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setRequestMethod("GET");& it works

Trying to fetch mysql data in android listview

Hello everyone I am trying to fetch data from mysql database in android ListView,
Following code is throwing java.lang.StringIndexOutOfBoundsException
I am new to Android Development, If anybody could guide me through this it will be much help.
Thank You.
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.InputStream;
import java.util.ArrayList;
import android.app.Activity;
import android.app.ProgressDialog;
import android.os.Bundle;
import android.util.Log;
import android.widget.ListView;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONArray;
import org.json.JSONObject;
import android.os.AsyncTask;
public class Main_catagory_one extends Activity{
Activity context;
HttpPost httppost;
StringBuffer buffer;
HttpResponse response;
HttpClient httpclient;
ProgressDialog pd;
CustomAdapter adapter;
ListView listProduct;
ArrayList<Product> records;
protected void onCreate(Bundle savedInstanceState) {
//TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main1);
context=this;
records=new ArrayList<Product>();
listProduct=(ListView)findViewById(R.id.listView1);
adapter=new CustomAdapter(context, R.layout.list_view,R.id.textView3,
records);
listProduct.setAdapter(adapter);
}
public void onStart(){
super.onStart();
//execute background task
BackTask bt=new BackTask();
bt.execute();
}
//background process to make a request to server and list product information
private class BackTask extends AsyncTask<Void,Void,Void>{
protected void onPreExecute(){
super.onPreExecute();
pd = new ProgressDialog(context);
pd.setTitle("Retrieving data");
pd.setMessage("Please wait.");
pd.setCancelable(true);
pd.setIndeterminate(true);
pd.show();
}
protected Void doInBackground(Void...params){
InputStream is=null;
String result="";
try{
httpclient=new DefaultHttpClient();
httppost= new HttpPost("http://10.0.2.2/fetch_item/getproducts.php");
response=httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
// Get our response as a String.
is = entity.getContent();
}catch(Exception e){
if(pd!=null)
pd.dismiss(); //close the dialog if error occurs
Log.e("ERROR", e.getMessage());
}
//convert response to string
try{
BufferedReader reader = new BufferedReader(new InputStreamReader(is,"utf-8"),8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line+"\n");
}
is.close();
result=sb.toString();
}catch(Exception e){
Log.e("ERROR", "Error converting result "+e.toString());
}
//parse json data
try{
// Remove unexpected characters that might be added to beginning of the string
result=result.substring(result.indexOf("["));
JSONArray jArray =new JSONArray(result);
for(int i=0;i<jArray.length();i++){
JSONObject json_data =jArray.getJSONObject(i);
Product p=new Product();
p.setpName(json_data.getString("Item_name"));
p.setuPrice(json_data.getString("Item_price"));
p.setpQauntity(json_data.getString("Item_quantity"));
p.setpImage(json_data.getString("Item_img"));
records.add(p);
}
}
catch(Exception e){
Log.e("ERROR", "Error pasting data "+e.toString());
}
return null;
}
protected void onPostExecute(Void result){
if(pd!=null) pd.dismiss(); //close dialog
Log.e("size", records.size() + "");
adapter.notifyDataSetChanged(); //notify the ListView to get new records
}
}
}
IndexOutOfBoundsException - if beginIndex is negative or larger than
the length of this String object.
You should get used to using the API. It tells you what exceptions a method throws and why.
Try printing length of the string before and after doing substring.
For example...
String testing = "Hello World";
System.out.println("Length of testing = " + testing.length);
System.out.println("Value of testing = " + testing);
testing.substring(1,2);

using AsyncTask i want the data in list view when calling restful api

I just build a demo application through async task and now i want the json data in list view so i dont know where i can add json functions and array list etc so plz guide me or help me by edit the code i thankful in advance and plz help im new to android and java
package your.packag.namespace;
import java.io.IOException;
import java.io.InputStream;
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.apache.http.protocol.BasicHttpContext;
import org.apache.http.protocol.HttpContext;
import android.app.Activity;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
public class runActivity extends Activity implements OnClickListener {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
findViewById(R.id.my_button).setOnClickListener(this);
}
#Override
public void onClick(View arg0) {
Button b = (Button)findViewById(R.id.my_button);
b.setClickable(false);
new LongRunningGetIO().execute();
}
private class LongRunningGetIO extends AsyncTask <Void, Void, String> {
protected String getASCIIContentFromEntity(HttpEntity entity) throws IllegalStateException, IOException {
InputStream in = entity.getContent();
StringBuffer out = new StringBuffer();
int n = 1;
while (n>0) {
byte[] b = new byte[4096];
n = in.read(b);
if (n>0) out.append(new String(b, 0, n));
}
return out.toString();
}
#Override
protected String doInBackground(Void... params) {
HttpClient httpClient = new DefaultHttpClient();
HttpContext localContext = new BasicHttpContext();
HttpGet httpGet = new HttpGet("http://192.168.1.156/recess/document/document");
HttpClient client = new DefaultHttpClient();
HttpResponse response=null;
try{
response = client.execute(httpGet);}
catch(Exception e){}
System.out.println(response.getStatusLine());
String text = null;
try {
response = httpClient.execute(httpGet, localContext);
HttpEntity entity = response.getEntity();
text = getASCIIContentFromEntity(entity);
} catch (Exception e) {
return e.getLocalizedMessage();
}
return text;
}
protected void onPostExecute(String results) {
if (results!=null) {
EditText et = (EditText)findViewById(R.id.my_edit);
et.setText(results);
}
Button b = (Button)findViewById(R.id.my_button);
b.setClickable(true);
}
}}
You can use the built-in org.json classes to convert the retrieved string (your text variable content) in to JSON objects.
Have a look at the tutorial from Lars Vogel on how to do that.

Populating a ListView w/ AsyncTask

This is probably not very elegant, but what I'm trying to do is connect to a web service, fetch the JSON, parse it, create an object out of it, add that object to an ArrayList and then use that ArrayList to populate my ListView.
I'm trying to do all of this with AsyncTask.
SUMMARY: doInBackgroud takes a String of a url, uses it to connect to a web service. I get the JSON data as a string, parse it, construct a new object out of the data, and add it to ArrayList. Then in onPostExecute I'm trying to set the listadapter using an ArrayAdapter that utilizes my ArrayList.
Here's what I have:
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.io.StringWriter;
import java.io.Writer;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.Arrays;
import org.json.JSONArray;
import org.json.JSONObject;
import oauth.signpost.OAuthConsumer;
import oauth.signpost.basic.DefaultOAuthConsumer;
import android.app.ListActivity;
import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.os.Bundle;
import android.widget.ArrayAdapter;
public class AllOffersListActivity extends ListActivity {
private static final String CONSUMER_KEY = "bla";
private static final String CONSUMER_SECRET = "bla";
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
new CreateArrayListTask().execute("http://example.com/sample.json");
}
private class CreateArrayListTask extends AsyncTask<String, Void, ArrayList<Offer>> {
private final ProgressDialog dialog = new ProgressDialog(AllOffersListActivity.this);
#Override
protected void onPreExecute() {
this.dialog.setMessage("Fetching offers...");
this.dialog.show();
}
#Override
protected ArrayList<Offer> doInBackGround(String...urls) {
ArrayList<Offer> offerList = new ArrayList<Offer>();
for(String url: urls) {
OAuthConsumer consumer = new DefaultOAuthConsumer(CONSUMER_KEY, CONSUMER_SECRET);
consumer.setTokenWithSecret("", "");
try {
URL url1 = new URL(url);
HttpURLConnection request = (HttpURLConnection) url1.openConnection();
// sign the request
consumer.sign(request);
// send the request
request.connect();
String JSONString = convertStreamToString(request.getInputStream());
JSONObject jObject = new JSONObject(JSONString);
JSONObject offerObject = jObject.getJSONObject("offer");
String titleValue = offerObject.getString("title");
//System.out.println(titleValue);
String descriptionValue = offerObject.getString("description");
//System.out.println(attributeValue);
JSONObject businessObject = offerObject.getJSONObject("business");
String nameValue = businessObject.getString("name");
Offer myOffer = new Offer(titleValue, descriptionValue, nameValue);
offerList.add(myOffer);
} catch (Exception e) {
e.printStackTrace();
}
}
return offerList;
}
#Override
protected void onPostExecute(ArrayList<Offer> offerList) {
if(this.dialog.isShowing())
this.dialog.dismiss();
setListAdapter(new ArrayAdapter<Offer>(AllOffersListActivity.this, android.R.layout.simple_list_item_1, offerList));
}
}
private String convertStreamToString(InputStream inputStream) throws IOException {
if(inputStream != null) {
Writer writer = new StringWriter();
char[] buffer = new char[1024];
try {
Reader reader = new BufferedReader( new InputStreamReader(inputStream, "UTF-8"));
int n;
while((n = reader.read(buffer)) != -1) {
writer.write(buffer, 0, n);
}
} finally {
inputStream.close();
}
return writer.toString();
} else {
return "";
}
}
}
I'm seeing two errors. One is on my private Async class: "The type AllOffersListActivity.CreateArrayListTask must implement the inherited abstract method AsyncTask<String,Void,ArrayList<Offer>>.doInBackground(String...)"
Secondly, on my doInBackGround Override, I'm getting: The method doInBackGround(String...) of type AllOffersListActivity.CreateArrayListTask must override or implement a supertype method
What am I missing here?
It's just a small typo; should be doInBackground instead of doInBackGround.
#LuxuryMode you have done mistake on doInBackGround
the correct spelling is doInBackground
asynctask must have to implement doInBackground method so it is not recognize this method because of wrong Name of method so it gives you error
The method doInBackGround(String...) of type AllOffersListActivity.CreateArrayListTask must
override or implement a supertype method

Categories

Resources