Android Studio: setOnItemClickListener - android

I have two AppCompatActivitys, both should have an onItemClickListener, but one of them doesn't do anything on click. I've just added a Toast for test reason, later on it should call a function to delete an item from list (with an ajax request)
What am I doing wrong?
I have made custom list and custom adapter for this - I know, I am new to Android Studio, but the other Activity works fine, and I cant find any differences.
public class ActivityListofProducts extends AppCompatActivity {
ProgressDialog pd;
SharedPreferences preferences;
String userid;
String session;
String list_id = "-1"; // or other values
String appVersion = "";
private ArrayList<listProductItem> myProducts = new ArrayList<listProductItem>();
private ArrayList<listProductItem> groceryFilterProducts = new ArrayList<listProductItem>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
handleIntent(getIntent());
setContentView(R.layout.activity_list_of_products);
this.setTitle(getString(R.string.grocery_list));
Bundle b = getIntent().getExtras();
SwipeRefreshLayout swipeRefreshLayout = (SwipeRefreshLayout) findViewById(R.id.refreshLayout);
if (b != null)
list_id = b.getString("list_id");
Toast.makeText(this, "List to open " + " " + list_id, Toast.LENGTH_SHORT).show();
preferences =
getSharedPreferences(this.getPackageName(), this.MODE_PRIVATE);
userid = preferences.getString("userid", "");
session = preferences.getString("session", "");
appVersion = preferences.getString("appVersion", "");
getData();
swipeRefreshLayout.setOnRefreshListener(
new SwipeRefreshLayout.OnRefreshListener() {
#Override
public void onRefresh() {
getData();
swipeRefreshLayout.setRefreshing(false);
}
}
);
}
public void getData() {
AsyncTask<String, String, String> Task_GetListofProducts = new Task_GetListofProducts();
Task_GetListofProducts.execute("https://get-some-json.com");
}
public void initListofProducts(String jsonString) {
Log.i("jsonString",jsonString);
try {
JSONObject jsonResponse = new JSONObject(jsonString);
JSONObject jsonListMode = jsonResponse.getJSONObject("list");
String ListName = jsonListMode.optString("name");
this.setTitle(ListName);
JSONArray jsonMainNode = jsonResponse.optJSONArray("data");
for (int i = 0; i < jsonMainNode.length(); i++) {
JSONObject jsonChildNode = jsonMainNode.getJSONObject(i);
int item_amount = jsonChildNode.optInt("item_amount");
int id = jsonChildNode.optInt("id");
String item_name = jsonChildNode.optString("item_name",">Name<");
int done = jsonChildNode.optInt("done", 0);
String timestamp = jsonChildNode.optString("timestamp", "");
String item_scale = jsonChildNode.optString("item_scale", "x");
String img = jsonChildNode.optString("img", "x");
double bestprice = jsonChildNode.optDouble("bestprice");
//int oitems = jsonChildNode.optInt("oitems", 0);
//int shared = jsonChildNode.optInt("shared", 0);
String outPut = "item_amount:"+ item_amount +" id:"+ id +" item_name:"+ item_name +" done:"+ done +" timestamp:"+ timestamp +" item_scale:"+ item_scale +" img:"+ img;
Log.i("outPut",outPut);
myProducts.add(new listProductItem(id, item_name, item_amount, item_scale, img, done, timestamp, bestprice));
}
final ListView lv = findViewById(R.id.grocery_list_of_products);
lv.setAdapter(new listofProductsAdapter(this, myProducts));
lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> a, View v, int position, long id) {
/*
!! HERE is my problem. This Code seems not to be executed !!
*/
Toast.makeText(ActivityListofProducts.this, "Should handle click now.", Toast.LENGTH_SHORT).show();
}
});
} catch (JSONException e) {
Toast.makeText(getApplicationContext(), "Error" + e.toString(), Toast.LENGTH_SHORT).show();
}
}
public void setProductDone(int pid, int done) {
String url = "put-some-json.com";
new ActivityListofProducts.Task_SetProductDone().execute(url);
}
private class Task_SetProductDone extends AsyncTask<String, String, String> {
protected void onPreExecute() {
super.onPreExecute();
pd = new ProgressDialog(ActivityListofProducts.this);
pd.setMessage("Please wait");
pd.setCancelable(false);
pd.show();
}
protected String doInBackground(String... params) {
HttpURLConnection connection = null;
BufferedReader reader = null;
Log.i("doInBackground",params.toString());
try {
URL url = new URL(params[0]);
connection = (HttpURLConnection) url.openConnection();
connection.connect();
InputStream stream = connection.getInputStream();
reader = new BufferedReader(new InputStreamReader(stream));
StringBuffer buffer = new StringBuffer();
String line = "";
while ((line = reader.readLine()) != null) {
buffer.append(line + "\n");
Log.d("Response: ", "> " + line); //here you will get whole response...... :-)
}
return buffer.toString();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (UnknownHostException e) {
Toast.makeText(ActivityListofProducts.this, "No Internet?", Toast.LENGTH_SHORT).show();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (connection != null) {
connection.disconnect();
}
try {
if (reader != null) {
reader.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
return null;
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
if (pd.isShowing()) {
pd.dismiss();
}
Log.i("onPostExecute", result);
}
}
private class Task_GetListofProducts extends AsyncTask<String, String, String> {
protected void onPreExecute() {
super.onPreExecute();
pd = new ProgressDialog(ActivityListofProducts.this);
pd.setMessage("Please wait");
pd.setCancelable(false);
pd.show();
myProducts = new ArrayList<listProductItem>(); //empty list
}
protected String doInBackground(String... params) {
HttpURLConnection connection = null;
BufferedReader reader = null;
Log.i("doInBackground",params.toString());
try {
URL url = new URL(params[0]);
connection = (HttpURLConnection) url.openConnection();
connection.connect();
InputStream stream = connection.getInputStream();
reader = new BufferedReader(new InputStreamReader(stream));
StringBuffer buffer = new StringBuffer();
String line = "";
while ((line = reader.readLine()) != null) {
buffer.append(line + "\n");
Log.d("Response: ", "> " + line); //here you will get whole response...... :-)
}
return buffer.toString();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (connection != null) {
connection.disconnect();
}
try {
if (reader != null) {
reader.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
return null;
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
if (pd.isShowing()) {
pd.dismiss();
}
initListofProducts(result);
}
}
private class Task_FindProducts extends AsyncTask<String, String, String> {
protected void onPreExecute() {
super.onPreExecute();
pd = new ProgressDialog(ActivityListofProducts.this);
pd.setMessage("Please wait");
pd.setCancelable(false);
pd.show();
myProducts = new ArrayList<listProductItem>(); //empty list
}
protected String doInBackground(String... params) {
HttpURLConnection connection = null;
BufferedReader reader = null;
Log.i("doInBackground",params.toString());
try {
URL url = new URL(params[0]);
connection = (HttpURLConnection) url.openConnection();
connection.connect();
InputStream stream = connection.getInputStream();
reader = new BufferedReader(new InputStreamReader(stream));
StringBuffer buffer = new StringBuffer();
String line = "";
while ((line = reader.readLine()) != null) {
buffer.append(line + "\n");
Log.d("Response: ", "> " + line); //here you will get whole response...... :-)
}
return buffer.toString();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (connection != null) {
connection.disconnect();
}
try {
if (reader != null) {
reader.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
return null;
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
if (pd.isShowing()) {
pd.dismiss();
}
setFilterProducts(result);
}
}
}

Related

Parse Json data into a Json object

I have a problem with parsing a tag inside a Json object.
My json code is structured like that:
{"giocatori":[{"nome":"Giovanni","cognome":"Muchacha","numero":"1","ruolo":"F-G"},
{"nome":"Giorgio","cognome":"Rossi","numero":"2","ruolo":"AG"},
{"nome":"Andrea","cognome":"Suagoloso","numero":"3","ruolo":"P"},
{"nome":"Salvatore","cognome":"Aranzulla","numero":"4","ruolo":"G"},
{"nome":"Giulio","cognome":"Muchacha","numero":"5","ruolo":"F"}]}
I got the code that let me get the Json file from here: Get JSON Data from URL Using Android? and I'm trying to parse a tag (for example the "nome" tag) into a Json object.
This is the code I got:
public class MainActivity extends AppCompatActivity {
Button btnHit;
TextView txtJson;
ProgressDialog pd;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btnHit = (Button) findViewById(R.id.btnHit);
txtJson = (TextView) findViewById(R.id.tvJsonItem);
btnHit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
new JsonTask().execute("https://api.myjson.com/bins/177dpo");
}
});
}
private class JsonTask extends AsyncTask<String, String, String> {
protected void onPreExecute() {
super.onPreExecute();
pd = new ProgressDialog(MainActivity.this);
pd.setMessage("Please wait");
pd.setCancelable(false);
pd.show();
}
protected String doInBackground(String... params) {
HttpURLConnection connection = null;
BufferedReader reader = null;
try {
URL url = new URL(params[0]);
connection = (HttpURLConnection) url.openConnection();
connection.connect();
InputStream stream = connection.getInputStream();
reader = new BufferedReader(new InputStreamReader(stream));
StringBuffer buffer = new StringBuffer();
String line = "";
while ((line = reader.readLine()) != null) {
buffer.append(line+"\n");
Log.d("Response: ", "> " + line);
}
return buffer.toString();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (connection != null) {
connection.disconnect();
}
try {
if (reader != null) {
reader.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
return null;
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
if (pd.isShowing()){
pd.dismiss();
}
txtJson.setText(result);
}
}
}
I've never worked with this type of file so I'll really appreciate your help!
You can use something like this:
try {
String servResponse = response.toString();
JSONObject parentObj = new JSONObject(servResponse);
JSONArray parentArray = parentObj.getJSONArray("giocatori");
if (parentArray.length() == 0) {
//if it's empty, do something (or not)
} else {
//Here, finalObj will have your jsonObject
JSONObject finalObj = parentArray.getJSONObject(0);
//if you decide to store some value of the object, you can do like this (i've created a nomeGiocatori for example)
nomeGiocatori = finalObj.getString("nome");
}
} catch (Exception e) {
Log.d("Exception: ", "UnknownException");
}
I use this kind of code all the time, works like a charm.

Asynctask android return contents "doinBackground

I would like to retrieve the contents of my variable "$content" in my activity.
But I don't know how to use the return value of my doinbackground.
Can you help me ?
thank you in advance
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
String restURL = "https://proxyepn-test.epnbn.net/wsapi/epn";
RestOperation test = new RestOperation();
test.execute(restURL);
}
private class RestOperation extends AsyncTask<String, Void, String> {
//final HttpClient httpClient = new DefaultHttpClient();
String content;
String error;
ProgressDialog progressDialog = new ProgressDialog(MainActivity.this);
String data = "";
TextView serverDataReceived = (TextView)findViewById(R.id.serverDataReceived);
TextView showParsedJSON = (TextView) findViewById(R.id.showParsedJSON);
// EditText userinput = (EditText) findViewById(R.id.userinput);
#Override
protected void onPreExecute() {
super.onPreExecute();
progressDialog.setTitle("Please wait ...");
progressDialog.show();
}
#Override
protected String doInBackground(String... params) {
BufferedReader br = null;
URL url;
try {
url = new URL(params[0]);
URLConnection connection = url.openConnection();
connection.setDoOutput(true);
OutputStreamWriter outputStreamWr = new OutputStreamWriter(connection.getOutputStream());
outputStreamWr.write(data);
outputStreamWr.flush();
br = new BufferedReader(new InputStreamReader(connection.getInputStream()));
StringBuilder sb = new StringBuilder();
String line = null;
while((line = br.readLine())!=null) {
sb.append(line);
sb.append(System.getProperty("line.separator"));
}
content = sb.toString();
} catch (MalformedURLException e) {
error = e.getMessage();
e.printStackTrace();
} catch (IOException e) {
error = e.getMessage();
e.printStackTrace();
} finally {
try {
br.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
return content;
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
progressDialog.dismiss();
if(error!=null) {
serverDataReceived.setText("Error " + error);
} else {
serverDataReceived.setText(content);
String output = "";
JSONObject jsonResponse;
try {
jsonResponse = new JSONObject(content);
JSONArray jsonArray = jsonResponse.names();
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject child = jsonArray.getJSONObject(i);
String name = child.getString("name");
String number = child.getString("number");
String time = child.getString("date_added");
output = "Name = " + name + System.getProperty("line.separator") + number + System.getProperty("line.separator") + time;
output += System.getProperty("line.separator");
Log.i("content",content);
}
showParsedJSON.setVisibility(View.INVISIBLE);
showParsedJSON.setText(output);
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
}
You can directly call to the method which exist in activity, from onPostExecute method of asynctask by passing "content" value.
#Override
protected void onPostExecute(String content) {
Activity.yourMethod(content);
}
If you want to return the value from asynctask you can use
content = test.execute(url).get();
but it is not a good practice of asynctask, because it is working as serial execution. So it is not fulfill the use of asynctask for palatalization.Because get() will block the UI thread.

How Can add a JSON Data to Array in JAVA

I have an project and I'm trying to convey to data from JSON Array to normal array. But I could not this. Can you help me if you know which and where code I add to in my project. My Main Activity file is here
public class MainActivity extends AppCompatActivity {
private TextView tvData;
private String[] stringArray;
protected ActionBarDrawerToggle mDrawerToggle;
private DrawerLayout mDrawerLayout;
private NavigationView mNavigationView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tvData = (TextView)findViewById(R.id.bilgi);
setupToolbar();
initNavigationDrawer();
new JSONTask().execute("http://192.168.1.36:8080/urunler/kategori_goster.php");
}
public class JSONTask extends AsyncTask<String,String,String>
{
#Override
protected String doInBackground(String... params) {
HttpURLConnection connection = null;
BufferedReader reader = null;
try {
URL url = new URL(params[0]);
connection = (HttpURLConnection) url.openConnection();
connection.connect();
InputStream stream = connection.getInputStream();
reader = new BufferedReader(new InputStreamReader(stream));
StringBuffer buffer = new StringBuffer();
String line="";
while((line = reader.readLine()) != null){
buffer.append(line);
}
String finalJson = buffer.toString();
JSONObject parentObject = new JSONObject(finalJson);
JSONArray parrentArray = parentObject.getJSONArray("uyelerimiz");
StringBuffer finalBufferedData = new StringBuffer();
for(int i=0;i<parrentArray.length(); i++)
{
JSONObject finalObject = parrentArray.getJSONObject(i);
String year = finalObject.getString("kategori_adi");
finalBufferedData.append(year + " \n");
}
return finalBufferedData.toString();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
} finally {
if(connection !=null)
{
connection.disconnect();
}
try {
if(reader !=null)
{
reader.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
return null;
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
tvData.setText(result);
}
}
JSON is working whitout any problem. I want to add my JSON data to my " private String[] stringArray;"
Here is how the JSON is formatted:
{
"uyelerimiz":[
{
"kategori_adi":"Bilgisayar"
},
{
"kategori_adi" ‌​:"Cep Telefonu"
},
{
"kategori_adi":"Saglik"
},
{
"kategori_adi":"Kirtas‌​iye"
}
]
}
private String[] parseJson(String response){
try {
JSONObject lJsonObject = new JSONObject(response);
JSONArray lJsonArray = lJsonObject.getJSONArray("uyelerimiz");
String[] lResult = new String[lJsonArray.length()];
for (int index = 0;index<lJsonArray.length();index++){
lResult[index] = lJsonArray.getJSONObject(index).getString("kategori_adi");
}
return lResult;
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}

i have API key but when i put it in my android studio to return me list its return me but nothing and i can sad that its return me json

public class GetPlaceSearchTask extends AsyncTask<String , Void ,String>
{
private Context context;
private ProgressDialog dialog;
public static final String SEND_RESULT_SEARCH_BROADCAST_FROM_TASK = "send_result_search";
private String API_LOCATION = "https://maps.googleapis.com/maps/api/place/nearbysearch/" +
"json?location=-33.8670522,151.1957362&radius=500&type=restaurant&name=cruise&key=";
public GetPlaceSearchTask(Context context) {
this.context = context;
}
protected void onPreExecute() {
if (context != null) {
dialog = new ProgressDialog(context);
dialog.setTitle("Downloading");
dialog.show();
}
}
#Override
protected String doInBackground(String... params) {
HttpsURLConnection connection = null;
BufferedReader reader = null;
StringBuilder builder = new StringBuilder();
try {
URL url = new URL(String.format(API_LOCATION, params[0], params[1]));
connection = (HttpsURLConnection) url.openConnection();
if (connection.getResponseCode() != HttpsURLConnection.HTTP_OK) {
return null;
}
reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
String line;
while ((line = reader.readLine()) != null) {
builder.append(line);
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
if (connection != null) {
connection.disconnect();
}
if (reader != null) {
try {
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return builder.toString();
}
#Override
protected void onPostExecute(String result) {
if (dialog != null) {
dialog.dismiss();
}
Intent intent = new Intent(SEND_RESULT_SEARCH_BROADCAST_FROM_TASK);
intent.putExtra("result_search", result);
LocalBroadcastManager.getInstance(context).sendBroadcast(intent);
}
public static class GetPlaceSearchTextTask extends AsyncTask<String , Void , String>{
private String API_TEXT = "https://maps.googleapis.com/maps/api/place/textsearch/" +
"json?query=%1$s&location=[%2$s,%3$s]&radius=5000&key=";
public static final String SEND_BROADCAST_RESULT_TEXT_FROM_TASK = "sand_text_result";
private Context context;
private ProgressDialog dialog ;
public GetPlaceSearchTextTask(Context context){
this.context = context;
}
#Override
protected void onPreExecute() {
if (context != null) {
dialog = new ProgressDialog(context);
dialog.setTitle("Downloading");
dialog.show();
}
}
#Override
protected String doInBackground(String... params) {
HttpsURLConnection connection = null;
BufferedReader reader = null;
StringBuilder builder = new StringBuilder() ;
try {
URL url = new URL(API_TEXT + params[0] + params[1] + params[2]) ;
connection = (HttpsURLConnection) url.openConnection();
if (connection.getResponseCode() != HttpsURLConnection.HTTP_OK){
return null;
}
reader = new BufferedReader(new InputStreamReader(connection.getInputStream())) ;
String line;
while ((line=reader.readLine())!= null){
builder.append(line);
}`enter code here`
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
if (connection!=null)
connection.disconnect();
if (reader!=null)
try {
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
return builder.toString();
}
#Override
protected void onPostExecute(String result_text) {
if (dialog!=null){
dialog.dismiss();
}`enter code here`
Intent intent = new Intent(SEND_BROADCAST_RESULT_TEXT_FROM_TASK);
intent.putExtra("text" , result_text);
LocalBroadcastManager.getInstance(context).sendBroadcast(intent);
}
}
}

How get return value from Thread?

I am using Thread for Webservice but i cant get the data from Thread because i cant return data from Thread.
This is my WebService.java :
public class Webservice {
static String result;
public static String readUrl(final String url) {
Thread thread = new Thread(new Runnable() {
#Override
public void run() {
try {
HttpClient client = new DefaultHttpClient();
HttpPost method = new HttpPost(url);
HttpResponse response = client.execute(method);
InputStream stream = response.getEntity().getContent();
result = ConvertInputStreamToString(stream);
Log.i("xxx","OK" + result);
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
});
thread.start();
return result;
}
private static String ConvertInputStreamToString(InputStream inputstteam) {
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(
inputstteam));
StringBuilder builder = new StringBuilder();
String line = "";
while ((line = reader.readLine()) != null) {
builder.append(line);
}
return builder.toString();
}
catch (IOException e) {
e.printStackTrace();
}
return null;
}
}
This is NotesActivity.java :
public class NotesActivity extends Activity {
private ArrayList<StructTask> nettasks = new ArrayList<StructTask>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Thread thread = new Thread(new Runnable() {
#Override
public void run() {
String result = Webservice.readUrl("http://192.168.200.101:8081/note-server/");
if (result != null) {
try {
JSONArray tasks = new JSONArray(result);
for (int i = 0; i < tasks.length(); i++) {
JSONObject object = tasks.getJSONObject(i);
//Log.i("LOG", "Task: " + object.getString("task_title"));
StructTask task = new StructTask();
task.id = object.getLong("task_id");
task.title = object.getString("task_title");
task.desc = object.getString("task_desc");
task.done = object.getBoolean("task_done");
nettasks.add(task);
for (StructTask taskes : nettasks) {
Log.i("LOG", "Taskes: " + taskes.id + "|" + taskes.title + "|" + taskes.desc + "|" + taskes.done);
}
}
} catch (JSONException e) {
e.printStackTrace();
}
}
else
{
Log.i("OK", "TaskesOK: " + result);
Log.i("LOG", "Task: " + "NULL");
}
}
});
thread.start();
}
}
This is my StructTask.java :
public class StructTask {
public long id;
public String title;
public String desc;
public boolean done;
}
This code return for me NULL .
Just try this way
1) Webservice.java
public class Webservice {
public interface WebCallListener{
void onCallComplete(String result);
}
public static void readUrl(final String url,final WebCallListener callListener) {
Thread thread = new Thread(new Runnable() {
#Override
public void run() {
try {
HttpClient client = new DefaultHttpClient();
HttpPost method = new HttpPost(url);
HttpResponse response = client.execute(method);
InputStream stream = response.getEntity().getContent();
callListener.onCallComplete(ConvertInputStreamToString(stream));
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
});
thread.start();
}
private static String ConvertInputStreamToString(InputStream inputstteam) {
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(
inputstteam));
StringBuilder builder = new StringBuilder();
String line = "";
while ((line = reader.readLine()) != null) {
builder.append(line);
}
return builder.toString();
}
catch (IOException e) {
e.printStackTrace();
}
return null;
}
}
2) NotesActivity.java
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Webservice.readUrl("http://192.168.200.101:8081/note-server/",new WebCallListener() {
#Override
public void onCallComplete(String result) {
if (result != null) {
try {
JSONArray tasks = new JSONArray(result);
for (int i = 0; i < tasks.length(); i++) {
JSONObject object = tasks.getJSONObject(i);
//Log.i("LOG", "Task: " + object.getString("task_title"));
StructTask task = new StructTask();
task.id = object.getLong("task_id");
task.title = object.getString("task_title");
task.desc = object.getString("task_desc");
task.done = object.getBoolean("task_done");
nettasks.add(task);
}
for (StructTask taskes : nettasks) {
Log.i("LOG", "Taskes: " + taskes.id + "|" + taskes.title + "|" + taskes.desc + "|" + taskes.done);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
else
{
Log.i("OK", "TaskesOK: " + result);
Log.i("LOG", "Task: " + "NULL");
}
}
});
}
You may use your code some thing like this:
private class ImageDownloader extends AsyncTask {
#Override
protected Bitmap doInBackground(String... param) {
// TODO Auto-generated method stub
return myBackgroundImageDownloadFun(param[0]);
}
#Override
protected void onPreExecute() {
Log.i("Async-Example", "onPreExecute Called");
simpleWaitDialog = ProgressDialog.show(ImageDownladerActivity.this,
"Wait", "Downloading Image");
}
#Override
protected void onPostExecute(Bitmap result) {
Log.i("Async-Example", "onPostExecute Called");
MyImageView.setImageBitmap(result);
simpleWaitDialog.dismiss();
}
For this you can use AsyncTask i.e,
private class Webservice extends AsyncTask<Void, Void, ArrayList<StructTask>> {
private ArrayList<StructTask> nettasks = new ArrayList<StructTask>();
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected ArrayList<StructTask> doInBackground(Void... params) {
try {
String result = readUrl("http://192.168.200.101:8081/note-server/");
JSONArray tasks = new JSONArray(result);
for (int i = 0; i < tasks.length(); i++) {
JSONObject object = tasks.getJSONObject(i);
//Log.i("LOG", "Task: " + object.getString("task_title"));
StructTask task = new StructTask();
task.id = object.getLong("task_id");
task.title = object.getString("task_title");
task.desc = object.getString("task_desc");
task.done = object.getBoolean("task_done");
nettasks.add(task);
}
for (StructTask taskes : nettasks) {
Log.i("LOG", "Taskes: " + taskes.id + "|" + taskes.title + "|" + taskes.desc + "|" + taskes.done);
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return nettasks;
}
/* after parsing response this method will be called*/
#Override
protected void onPostExecute(ArrayList<StructTask> result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
}
private String readUrl(String url) throws Exception{
HttpClient client = new DefaultHttpClient();
HttpPost method = new HttpPost(url);
HttpResponse response = client.execute(method);
InputStream stream = response.getEntity().getContent();
String result = ConvertInputStreamToString(stream);
Log.i("xxx", "OK" + result);
return result;
}
private String ConvertInputStreamToString(InputStream inputstteam) {
try {
BufferedReader reader = new BufferedReader(
new InputStreamReader(inputstteam));
StringBuilder builder = new StringBuilder();
String line = "";
while ((line = reader.readLine()) != null) {
builder.append(line);
}
return builder.toString();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
}
In your activity class in onCreate method try to call like this
Webservice service=new Webservice();
service.excute();
so it will starts the excution of the above thread.
i think this will helps you

Categories

Resources