Receive argument Arraylist in android - java

I am writing a small ftp client using apache lib. I am returning list of files in ArrayList
import java.io.IOException;
import java.net.SocketException;
import java.util.ArrayList;
import java.util.List;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPFile;
import org.apache.commons.net.ftp.FTPReply;
import android.os.AsyncTask;
import android.util.Log;
public class myftpTask extends AsyncTask<String, Void, List<FTPFile>> {
public FTPFile[] FTPFile;
FTPClient mFtp = new FTPClient();
#Override
protected List<FTPFile> doInBackground(String... params) {
List<FTPFile> myFiles = new ArrayList<FTPFile>();
// TODO Auto-generated method stub
try {
mFtp.connect(params[0], 21);
if (FTPReply.isPositiveCompletion(mFtp.getReplyCode())) {
mFtp.login(params[1], params[2]);
mFtp.enterLocalPassiveMode();
mFtp.changeWorkingDirectory("/public_html");
FTPFile files[] = mFtp.listFiles();
for (int i = 0; i < files.length; i++) { // does not enter here
//Log.d("F-> " , ((FTPFile) files[i]).getName().toString());
//myFiles.add((FTPFile) files[i]).getName().toString());
myFiles.add(files[i]);
}
Log.v("Files", myFiles.toString());
mFtp.disconnect();
}
} catch (SocketException e) {
try {
mFtp.disconnect();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
//return 1;
return myFiles;
}
}
And I am receiving it like this
import java.util.List;
import org.apache.commons.net.ftp.FTPFile;
import android.app.Activity;
import android.os.Bundle;
import android.view.Menu;
import android.widget.ArrayAdapter;
import android.widget.ListView;
public class MainActivity extends Activity {
#SuppressWarnings("unchecked")
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ListView lv = (ListView) findViewById(R.id.listView1);
List<FTPFile> listofFiles;
listofFiles = (List<FTPFile>) new myftpTask().execute(
"*****", "*****", "******");
ArrayAdapter<FTPFile> arrayAdapter = new ArrayAdapter<FTPFile>(this,
android.R.layout.simple_list_item_1, listofFiles);
lv.setAdapter(arrayAdapter);
}
}
But it throwing an exception of cannot cast to list.
Where is the problem?
Regards

does this compile
listofFiles = (List<FTPFile>) new myftpTask().execute(
"*****", "*****", "******");
???
newmyftpTask().execute(); returns object from this type AsyncTask<String, Void, List<FTPFile>>
use this instead
listofFiles = (List<FTPFile>) new myftpTask().execute(
"*****", "*****", "******").get();

PROBLEM :
listofFiles = (List<FTPFile>) new myftpTask().execute(
"*****", "*****", "******");
you are cast wrong way
SOLUTION 1:
use get () method for getting result back from AsyncTask in main UI Thread as:
listofFiles = (List<FTPFile>) new myftpTask().execute(
"*****", "*****", "******").get();
NOTE :
this solution pause your main thread execution until response not come back from AsyncTask as doc says
SOLUTION 2:
use onPostExecute(List<FTPFile> result) for updating Ui without hanging of Ui when AsyncTask execution complete
just change your code as:
public class myftpTask extends AsyncTask<String, Void, List<FTPFile>> {
//your code here
#Override
protected void onPostExecute(List<FTPFile> result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
ArrayAdapter<FTPFile> arrayAdapter = new ArrayAdapter<FTPFile>(this,
android.R.layout.simple_list_item_1, result);
lv.setAdapter(arrayAdapter);
}
}
and start myftpTask task as from main Activity :
public class MainActivity extends Activity {
ListView lv;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ListView lv = (ListView) findViewById(R.id.listView1);
new myftpTask().execute("*****", "*****", "******");
}
}

For getting return value from AsyncTask you have to use its get() method,
Replace,
listofFiles = (List<FTPFile>) new myftpTask().
execute("*****", "*****", "******");
With,
listofFiles = (List<FTPFile>) new myftpTask().
execute("*****", "*****", "******").get();
But, this will block your UI Thread. So, better would be to create an Interface or BroadCastReceiver to return the value/data from AsyncTask. Here is a demo for the same.

Related

Issue with Http Client in android studio

I am new to android app development, and one of my clients asked me to fix this code his past dev left the job . there were a lot of errors I was able to fix it. But now I am stuck at a point in HTTP request error in java and cannot execute this code. Let me know how to fix it. Current status complied SDK 33 and cannot downgrade the same. Code below. HTTP client is deprecated.
package com.ecom.ecommerce;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.util.ArrayList;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpUriRequest;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.HttpConnectionParams;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.ActionBar;
import android.app.Activity;
import android.content.Intent;
import android.content.res.Configuration;
import android.graphics.drawable.ColorDrawable;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.GridView;
import android.widget.ProgressBar;
import android.widget.TextView;
public class ActivityCategoryList extends Activity {
GridView listCategory;
ProgressBar prgLoading;
TextView txtAlert;
// declare adapter object to create custom category list
AdapterCategoryList cla;
// create arraylist variables to store data from server
static ArrayList<Long> Category_ID = new ArrayList<Long>();
static ArrayList<String> Category_name = new ArrayList<String>();
static ArrayList<String> Category_image = new ArrayList<String>();
String CategoryAPI;
int IOConnect = 0;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.category_list);
ActionBar bar = getActionBar();
bar.setBackgroundDrawable(new
ColorDrawable(getResources().getColor(R.color.header)));
bar.setDisplayHomeAsUpEnabled(true);
bar.setHomeButtonEnabled(true);
bar.setTitle("Category");
prgLoading = (ProgressBar) findViewById(R.id.prgLoading);
listCategory = (GridView) findViewById(R.id.listCategory);
txtAlert = (TextView) findViewById(R.id.txtAlert);
cla = new AdapterCategoryList(ActivityCategoryList.this);
// category API url
CategoryAPI = Constant.CategoryAPI+"?accesskey="+Constant.AccessKey;
// call asynctask class to request data from server
new getDataTask().execute();
// event listener to handle list when clicked
listCategory.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> arg0, View arg1, int position,
long arg3) {
// TODO Auto-generated method stub
// go to menu page
Intent iMenuList = new Intent(ActivityCategoryList.this, ActivityMenuList.class);
iMenuList.putExtra("category_id", Category_ID.get(position));
iMenuList.putExtra("category_name", Category_name.get(position));
startActivity(iMenuList);
overridePendingTransition(R.anim.open_next, R.anim.close_next);
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_category, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
switch (item.getItemId()) {
case R.id.cart:
// refresh action
Intent iMyOrder = new Intent(ActivityCategoryList.this, ActivityCart.class);
startActivity(iMyOrder);
overridePendingTransition (R.anim.open_next, R.anim.close_next);
return true;
case R.id.refresh:
IOConnect = 0;
listCategory.invalidateViews();
clearData();
new getDataTask().execute();
return true;
case android.R.id.home:
// app icon in action bar clicked; go home
this.finish();
overridePendingTransition(R.anim.open_main, R.anim.close_next);
return true;
default:
return super.onOptionsItemSelected(item);
}
}
// clear arraylist variables before used
void clearData(){
Category_ID.clear();
Category_name.clear();
Category_image.clear();
}
// asynctask class to handle parsing json in background
public class getDataTask extends AsyncTask<Void, Void, Void>{
// show progressbar first
getDataTask(){
if(!prgLoading.isShown()){
prgLoading.setVisibility(0);
txtAlert.setVisibility(8);
}
}
#Override
protected Void doInBackground(Void... arg0) {
// TODO Auto-generated method stub
// parse json data from server in background
parseJSONData();
return null;
}
#Override
protected void onPostExecute(Void result) {
// TODO Auto-generated method stub
// when finish parsing, hide progressbar
prgLoading.setVisibility(8);
// if internet connection and data available show data on list
// otherwise, show alert text
if((Category_ID.size() > 0) && (IOConnect == 0)){
listCategory.setVisibility(0);
listCategory.setAdapter(cla);
}else{
txtAlert.setVisibility(0);
}
}
}
// method to parse json data from server
public void parseJSONData(){
clearData();
try {
// request data from Category API
HttpClient client = new DefaultHttpClient();
HttpConnectionParams.setConnectionTimeout(client.getParams(), 15000);
HttpConnectionParams.setSoTimeout(client.getParams(), 15000);
HttpUriRequest request = new HttpGet(CategoryAPI);
HttpResponse response = client.execute(request);
InputStream atomInputStream = response.getEntity().getContent();
BufferedReader in = new BufferedReader(new InputStreamReader(atomInputStream));
String line;
String str = "";
while ((line = in.readLine()) != null){
str += line;
}
// parse json data and store into arraylist variables
JSONObject json = new JSONObject(str);
JSONArray data = json.getJSONArray("data");
for (int i = 0; i < data.length(); i++) {
JSONObject object = data.getJSONObject(i);
JSONObject category = object.getJSONObject("Category");
Category_ID.add(Long.parseLong(category.getString("Category_ID")));
Category_name.add(category.getString("Category_name"));
Category_image.add(category.getString("Category_image"));
Log.d("Category name", Category_name.get(i));
}
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
IOConnect = 1;
e.printStackTrace();
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
#Override
protected void onDestroy() {
// TODO Auto-generated method stub
//cla.imageLoader.clearCache();
listCategory.setAdapter(null);
super.onDestroy();
}
#Override
public void onConfigurationChanged(final Configuration newConfig)
{
// Ignore orientation change to keep activity from restarting
super.onConfigurationChanged(newConfig);
}
#Override
public void onBackPressed() {
// TODO Auto-generated method stub
super.onBackPressed();
finish();
overridePendingTransition(R.anim.open_main, R.anim.close_next);
}
}

Pass global variable to php file through AsyncTask in Android Studio

I am currently populating a RrecyclerView from a remote database but wish to only query the database for dates based on a users ID. I have the userID assigned as a global variable on the LoginActivty of the app but I'm not sure where to pass that information to the php page from my DateActivity.
My Code for the DateActivity is as follows:
import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.widget.Toast;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
public class DateActivity extends AppCompatActivity {
public static String globex_num;
// CONNECTION_TIMEOUT and READ_TIMEOUT are in milliseconds
public static final int CONNECTION_TIMEOUT = 10000;
public static final int READ_TIMEOUT = 15000;
private RecyclerView mRVDateList;
private AdapterDate mAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_date);
//Make call to AsyncTask
new AsyncFetch().execute();
}
private class AsyncFetch extends AsyncTask<String, String, String> {
ProgressDialog pdLoading = new ProgressDialog(DateActivity.this);
HttpURLConnection conn;
URL url = null;
#Override
protected void onPreExecute() {
super.onPreExecute();
//this method will be running on UI thread
pdLoading.setMessage("\tLoading...");
pdLoading.setCancelable(false);
pdLoading.show();
}
#Override
protected String doInBackground(String... params) {
try {
url = new URL("thephpfile.com");
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return e.toString();
}
try {
// Setup HttpURLConnection class to send and receive data from php and mysql
conn = (HttpURLConnection) url.openConnection();
conn.setReadTimeout(READ_TIMEOUT);
conn.setConnectTimeout(CONNECTION_TIMEOUT);
conn.setRequestMethod("GET");
// setDoOutput to true as we recieve data from json file
conn.setDoOutput(true);
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
return e1.toString();
}
try {
int response_code = conn.getResponseCode();
// Check if successful connection made
if (response_code == HttpURLConnection.HTTP_OK) {
// Read data sent from server
InputStream input = conn.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(input));
StringBuilder result = new StringBuilder();
String line;
while ((line = reader.readLine()) != null) {
result.append(line);
}
// Pass data to onPostExecute method
return (result.toString());
} else {
return ("unsuccessful");
}
} catch (IOException e) {
e.printStackTrace();
return e.toString();
} finally {
conn.disconnect();
}
}
#Override
protected void onPostExecute(String result) {
//this method will be running on UI thread
pdLoading.dismiss();
List<DataDate> data=new ArrayList<>();
pdLoading.dismiss();
try {
JSONArray jsonArray = new JSONArray(result);
// Extract data from json and store into ArrayList as class objects
for(int i=0;i<jsonArray.length();i++){
JSONObject json_data = jsonArray.getJSONObject(i);
DataDate dateData = new DataDate();
dateData.date= json_data.getString("date");
data.add(dateData);
}
// Setup and Handover data to recyclerview
mRVDateList = (RecyclerView)findViewById(R.id.dateList);
mAdapter = new AdapterDate(DateActivity.this, data);
mRVDateList.setAdapter(mAdapter);
mRVDateList.setLayoutManager(new LinearLayoutManager(DateActivity.this));
} catch (JSONException e) {
Toast.makeText(DateActivity.this, e.toString(), Toast.LENGTH_LONG).show();
}
}
}
}
I solved the problem by passing it though the link.
url = new URL(www.thephpfile.php?userID=" + LoginActivity.userID);
At the start of the php file I did the following:
$userID = $_GET['userID'];

Android - after notifyDataSetChanged ListView remains blank

It's hours I search for something, but it doesn't seem to help.. Android Studio doesn't launch any error, but the screen remains blank. Why?
package org.newapp;
import android.os.AsyncTask;
import android.os.Bundle;
import android.app.Activity;
import android.util.Log;
import android.view.Menu;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import org.xml.sax.SAXException;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import saxrssreader.*;
public class MainActivity extends Activity {
private ArrayAdapter<RssItem> rssItemsArrayAdapter;
ListView codeLearnLessons;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
RssItem[] rssItems = new RssItem[]{};
rssItemsArrayAdapter = new ArrayAdapter<RssItem>(this, android.R.layout.simple_list_item_1, rssItems);
new WebCall().execute(rssItems);
codeLearnLessons = (ListView)findViewById(R.id.listView1);
codeLearnLessons.setAdapter(rssItemsArrayAdapter);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
private class WebCall extends AsyncTask<RssItem, Void, Void> {
#Override
protected Void doInBackground(RssItem... items) {
URL url = null;
try {
url = new URL("http://www.somewpsite.com/feed");
} catch (MalformedURLException e) {
e.printStackTrace();
}
try {
ArrayList<RssItem> listItems = RssReader.read(url).getRssItems();
items = listItems.toArray(new RssItem[listItems.size()]);
final int l = items.length;
runOnUiThread(new Runnable() {
#Override
public void run() {
codeLearnLessons.invalidateViews();
rssItemsArrayAdapter.notifyDataSetChanged();
Log.i("rec", "rec" + l);
}
});
} catch (SAXException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPreExecute() {
/*ProgressDialog mDialog = new ProgressDialog(MainActivity.this);
mDialog.setMessage("Please wait...");
mDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
mDialog.setIndeterminate(true);
mDialog.setCancelable(false);
mDialog.show();*/
}
}
}
The issue is that your using a ArrayList which only has scope inside of the AsyncTask.doInBackground() method. Since it is not given to the adapter, the notifyDataSetChanged() does nothing. You'll need to replace the existing array like this:
rssItemsArrayAdapter.clear();
rssItemsArrayAdapter.addAll(listItems);
rssItemsArrayAdapter.notifyDataSetChanged();
Having said that, you also really need to change your use of AsyncTask. There's no need to call runOnUiThread() from within your doInBackground() as the AsyncTask will automatically run its onPostExecute() on the UI thread. Have your doInBackground() method return your new ArrayList<RssItem> and create an onPostExecute() override method which adjusts the adapter as shown above.
You are passing your items to the AsyncTask but in the AsyncTask you declare them new with the content of your result. You never pass the items to your ArrayAdapter back. Make them a property of your class instance.
Edit - Example:
rssItemsArrayAdapter.clear();
rssItemsArrayAdapter.addAll(items);
and afterwards
rssItemsArrayAdapter.notifyDataSetChanged();

Limiting what jsoup retrieves

I'm Having fun learning to use jsoup and have successfully retrieved and displayed data from a website, but now I would like some further guidance on it if anyone can help.
Using the code below returns all the table rows 30+, How can I retrieve only say the first 10 of those rows?
also
When returning those rows and the data on them there are gaps/spaces in the row between the data, the spaces between rows are fine but its the spaces within the row that I want to get rid of, how can I omit those spaces/gaps?
My code so far...
package com.example.shiftzer;
import java.io.IOException;
import java.util.ArrayList;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import android.app.Activity;
import android.content.SharedPreferences;
import android.os.AsyncTask;
import android.os.Bundle;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TextView;
public class MainActivity extends Activity{
TextView textView1;
ListView shippingList;
public static final String APP_PREFERENCES = "AppPrefs";
SharedPreferences settings;
SharedPreferences.Editor prefEditor;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main_activity);
//rest of the code
textView1 = (TextView)findViewById(R.id.textView1);
shippingList = (ListView) findViewById(R.id.listView1);
settings = getSharedPreferences(APP_PREFERENCES, MODE_PRIVATE);
prefEditor = settings.edit();
new VTSTask().execute();//starts AsyncTask in private class VTSTask to get shipping info
}
private class VTSTask extends AsyncTask<Void, Void, ArrayList<String>> {
ArrayList<String> arr_shipping=new ArrayList<String>();
/**
* #param args
*/
#Override
protected ArrayList<String> doInBackground(Void... params) {
Document doc;
String shippingList;
try {
doc = Jsoup.connect("https://vts.mhpa.co.uk/main_movelistb.asp").get();
Elements tableRows = doc.select("table.dynlist tr td");
for (Element element : tableRows) {
shippingList = element.text();
arr_shipping.add(shippingList);// add value to ArrayList
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return arr_shipping;//<< Return ArrayList from here
}
#Override
protected void onPostExecute(ArrayList<String> result) {
//TextView tVShipping= (TextView)findViewById(R.id.textView2);
shippingList = (ListView) findViewById(R.id.listView1);
ArrayAdapter<String> adapter =
new ArrayAdapter<String>(MainActivity.this,
android.R.layout.simple_list_item_1,
android.R.id.text1);
for (String shipping_result : result)
{
adapter.add(shipping_result);
}
// Assign adapter to ListView
shippingList.setAdapter(adapter);
}
}
}
Thank you.
EDIT:
try {
doc = Jsoup.connect("https://vts.mhpa.co.uk/main_movelistb.asp").get();
Elements tableRows = doc.select("table.dynlist tr td");
tableRows.size();
for(int i = 0; i < 10; i++){
tableRows.get(i);
shippingList = tableRows.get(i).text() +"\n";
arr_shipping.add(shippingList);// add value to ArrayList
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return arr_shipping;//<< return ArrayList from here
}
Instead of doing for(Element element:tableRows), Elements has a size method.
So, you should be able to just do some validation with the size, and then simply
for(int i = 0; i < 10; i++){
tableRows.get(i);
}
to get 10 of them.
As for the spaces, before you store them in your arraylist just use regular expressions and remove the spaces.
http://www.vogella.com/articles/JavaRegularExpressions/article.html
Try This
import java.io.IOException;
import java.util.ArrayList;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.select.Elements;
public class test
{
static ArrayList<String> arr_shipping=new ArrayList<String>();
public static void main(String args[]) throws IOException
{
try {
Document doc = Jsoup.connect("https://vts.mhpa.co.uk/main_movelistb.asp").timeout(600000).get();
Elements tableRows = doc.select("table.dynlist tr:not(:eq(0))");
tableRows.size();
for(int i = 0; i < 10; i++){
//tableRows.get(i);
String shippingList =tableRows.get(i).text() +"\n";
arr_shipping.add(shippingList);// add value to ArrayList
System.out.println(shippingList);
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// return arr_shipping;//<< return ArrayList from here
}
}
Try this
doc.select("table.dynlist tr:lt(10)");
to limt the results.
Reference

android socket connection failed? [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 6 years ago.
Improve this question
Im' writing a sample chat program that sends message between 2 android phones, so I wrote the following and let a phone connect to itself(10.0.2.2 or localhost) to test it the code works or not.
But looks like in the thread of receivemsg(), the socket is never connected. So did I use the wrong ip address to refer to myself? or does my code have something wrong? thank you for your help!
package com.example.chatroomprogram;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.UnknownHostException;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
public class ClientActivity extends Activity {
private Handler handler = new Handler();
public ListView msgView;
public ArrayAdapter<String> msgList;
// public ArrayAdapter<String> msgList=new ArrayAdapter<String>(this,
// android.R.layout.simple_list_item_1);;
public String ipaddress;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_client);
Intent intent = getIntent();
ipaddress=intent.getStringExtra("ipaddress");
Log.i("123","ip is "+ipaddress);
msgView = (ListView) findViewById(R.id.listView);
msgList = new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1);
msgView.setAdapter(msgList);
// msgView.smoothScrollToPosition(msgList.getCount() - 1);
Button btnSend = (Button) findViewById(R.id.btn_Send);
receiveMsg();
btnSend.setOnClickListener(new View.OnClickListener() {
#SuppressLint("NewApi")
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
final EditText txtEdit = (EditText) findViewById(R.id.txt_inputText);
//msgList.add(txtEdit.getText().toString());
sendMessageToServer(txtEdit.getText().toString());
msgView.smoothScrollToPosition(msgList.getCount() - 1);
}
});
// receiveMsg();
//----------------------------
//server msg receieve
//-----------------------
//End Receive msg from server//
}
public void sendMessageToServer(String str) {
final String str1=str;
new Thread(new Runnable() {
#Override
public void run() {
//String host = "opuntia.cs.utep.edu";
//String host="10.0.";
String host2 = "10.0.2.2";
PrintWriter out = null;
Socket socket = null;
try {
socket = new Socket("10.0.2.2", 8008);
} catch (UnknownHostException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
out = new PrintWriter(socket.getOutputStream());
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Log.i("123","not null");
// out.println("hello");
out.println(str1);
Log.i("123", "hello");
out.flush();
}
}).start();
}
public void receiveMsg()
{
new Thread(new Runnable()
{
#Override
public void run() {
// TODO Auto-generated method stub
//final String host="opuntia.cs.utep.edu";
final String host="10.0.2.2";
//final String host="127.0.0.1";
Socket socket = null ;
BufferedReader in = null;
try {
//socket = new Socket(host,8008);
ServerSocket ss = new ServerSocket(8008);
socket = ss.accept();
} catch (UnknownHostException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
while(true)
{
String msg = null;
try {
msg = in.readLine();
Log.i("123","MSGGG: "+ msg);
//msgList.add(msg);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
if(msg == null)
{
break;
}
else
{
displayMsg(msg);
}
}
}
}).start();
}
public void displayMsg(String msg)
{
final String mssg=msg;
handler.post(new Runnable() {
#SuppressLint("NewApi")
#Override
public void run() {
// TODO Auto-generated method stub
msgList.add(mssg);
msgView.setAdapter(msgList);
msgView.smoothScrollToPosition(msgList.getCount() - 1);
Log.i("123","hi");
}
});
}
}
update: Problem solved, conclusion: if you use AVD, just use 10.0.2.2; if you use an actual phone to debug, you can use localhost
my bad... i used 10.0.2.2 and it works...

Categories