- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我试图找出为什么我的输入流无法正常工作。我正在尝试连接到服务器并获取 JSON 字符串并将其保存到变量 inputJSON 中。但是 inputJOSN 是空的,因为我的输入流无法正常工作。这行代码:
inputJSON = ConvertByteArrayToString(getBytesFromInputStream(inputStr));
似乎无法正常工作,我不确定为什么?
public class AndroidClient extends ProfileActivity {
private TextView textIn;
public Thread rt;
public Socket socket = null;
public PrintWriter outputstrwr;
public OutputStream out = null;
public DataOutputStream dataOutputStream = null;
public DataInputStream dataInputStream = null;
public InputStream inputStr = null;
private final static String LOG_TAG = AndroidClient.class.getSimpleName();
private final Handler handler = new Handler();
private List<Profile> serviceInfoList = new ArrayList<Profile>();
// Map between list position and profile
private Map<Integer, Profile> posMap = new HashMap<Integer, Profile>();
private Map<String, Integer> addressMap = new HashMap<String, Integer>();
private static String profilePicBase64Str="";
private String inputJSON = "";
private String outputJSON = "";
private String outputJSONserv = "";
private Profile p;
//String urlInputStream = "";
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Log.e(LOG_TAG, "Before OnCreate() Try");
try {
Log.e(LOG_TAG, "In OnCreate() Try");
socket = new Socket("23.23.175.213", 9000); //Port 1337
Log.e(LOG_TAG, "Created Socket");
dataOutputStream = new DataOutputStream(socket.getOutputStream());
Log.e(LOG_TAG, "Created DataOutputStream");
dataInputStream = new DataInputStream(socket.getInputStream());
Log.e(LOG_TAG, "Created DataInputStream");
//out = new OutputStream();
out = socket.getOutputStream();
inputStr = socket.getInputStream();
//Thread readjsonthrd = new Thread(new ReadJSONThread());
//inputstrrd = new InputStreamReader(socket.getInputStream());
p = new Profile();
Log.e(LOG_TAG, "Created Profile Instance");
//Gets the local profile via JSON and converts into Profile type
Gson gson = new Gson();
Log.e(LOG_TAG, "Created Gson Instance" + "GetProfileJSONStr:" + p.getProfileJSONStr());
p = gson.fromJson(p.getProfileJSONStr(), Profile.class);
setProfile(p);
Log.e(LOG_TAG, "Converted Profile to JSON");
//Gson gson = new Gson();
Log.e(LOG_TAG, "Before: outputJSON = gson.toJson(p);");
outputJSON = gson.toJson(p).toString();
outputJSON = removeExcessStr(outputJSON);
Log.e(LOG_TAG, "ProfilePicStr Base64:"+p.getProfilePicStr());
outputJSON = outputJSON.replace("Name","name");
outputJSON = outputJSON.replace("TagLine","message");
outputJSON = outputJSON.replace("Title","title");
outputJSON = outputJSON.replace("Company", "company");
outputJSON = outputJSON.replace("Industry","industry");
outputJSON = outputJSON.replace("WhatIDo","whatido");
outputJSON = outputJSON.replace("WhoDoIWantToMeet","meetwho");
outputJSON = outputJSON.replace("WHOOZNEAR_PROFILEPIC","photo");
outputJSON = outputJSON.replaceAll("[c][o][n][t][e][n][t][:][/][/][a-zA-Z0-9]+[/][a-zA-Z0-9]+[/][a-zA-Z0-9]+[/][a-zA-Z0-9]+[/][a-zA-Z0-9]+", getPicBase64Str()); /*"helloworld2"*/
if (!outputJSON.contains(",\"photo\":")) {
outputJSON = outputJSON.replace("}",",\"photo\":"+"\"IconnexUs\"}");
outputJSON = outputJSON.replace("}",",\"photo\":"+"\""+getPicBase64Str()+"\"}");
outputJSON = outputJSON.replace("}",",\"status\":\"enabled\"}");
}
else {
outputJSON = outputJSON.replace("}",",\"status\":\"enabled\"");
}
outputJSONserv = "{\"to\":\"broadcast\",\"type\":\"1\",\"payload\":"+outputJSON+"}";
Log.e(LOG_TAG, "Created outputJSON:" + outputJSON);
Log.e(LOG_TAG, "Created outputJSON Server:" + outputJSONserv);
JSONObject outObject = new JSONObject();
try {
outObject.put("photo", "hello");
outObject.put("type", "50");
outObject.put("payload", outputJSON);
outputJSON = gson.toJson(outObject).toString();
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Log.e(LOG_TAG, "Value of PROFILEPIC STRING FROM PROFILEMAP: "+profileMap.get("WHOOZNEAR_PROFILEPIC"));
p.setProfilePicStr(ConvertandSetImagetoBase64(profileMap.get("WHOOZNEAR_PROFILEPIC")));
//String headerJSON = gson.toJson(outObject).toString();
outputJSON = outputJSON.substring(nthOccurrence(outputJSON, '{', 2)-1, nthOccurrence(outputJSON, '}', 1)-1);
String input = "["+"Ryan"+"[";
//"[foo".replaceAll(Pattern.quote("["), "\"");
String result = input.replaceAll(Pattern.quote("["), "\"");
Log.e(LOG_TAG, "REGEX REPLACEALL:"+result);
outputstrwr = new PrintWriter(new OutputStreamWriter(socket.getOutputStream()), true);
outputstrwr.write(outputJSONserv);
Log.e(LOG_TAG, "Base64 String:"+p.getProfilePicStr());
Log.e(LOG_TAG, "Sent dataOutputStream");
} catch (UnknownHostException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Log.e(LOG_TAG, "Before initEventHandlers");
initEventHandlers();
Log.e(LOG_TAG, "After initEventHandlers");
//refreshViewModels();
Log.e(LOG_TAG, "Start Repeat Thread");
rt = new Thread(new RepeatingThread());
rt.start();
Log.e(LOG_TAG, "Started Repeat Thread");
}
@Override
public void onDestroy() {
super.onDestroy();
rt.stop();
try {
socket.close();
dataOutputStream.close();
dataInputStream.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
@Override
public void onPause(){
super.onPause();
rt.stop();
}
@Override
public void onResume(){
super.onResume();
if (rt.isAlive() == false) {
//rt.start();
}
}
@Override
public void onStop(){
super.onStop();
rt.stop();
try {
socket.close();
dataOutputStream.close();
dataInputStream.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public static String removeExcessStr(String json_excess) {
//String myString = myString.replace("=\"ppshein\"", "");
String json_excess1 = json_excess.replace("\"nameValues\":{", "");
String myString = json_excess1.replace(",\"profileId\":1,\"valid\":false}", "");
return myString;
}
public static String adddblquotattr(String attr) {
String result = attr.replaceAll(Pattern.quote("["), "\"");
return result;
}
public static String adddblquotval(String val) {
String result = val.replaceAll(Pattern.quote("["), "\"");
return result;
}
public static int nthOccurrence(String str, char c, int n) {
int pos = str.indexOf(c, 0);
while (n-- > 0 && pos != -1)
pos = str.indexOf(c, pos+1);
return pos;
}
public void setPicBase64Str(String profilePicBase64Str) {
this.profilePicBase64Str = profilePicBase64Str;
}
public String getPicBase64Str() {
return profilePicBase64Str;
}
public String ConvertandSetImagetoBase64(String imagePath) {
String base64 = null;
byte[] input = null;
try{
FileInputStream fd = new FileInputStream(imagePath);
Bitmap bmt = BitmapFactory.decodeFileDescriptor(fd.getFD());
try{
ByteArrayOutputStream stream = new ByteArrayOutputStream();
Bitmap tmp = ProfileActivity.scaleDownBitmap(bmt, 10, this);
tmp.compress(Bitmap.CompressFormat.JPEG, 10, stream);
input = stream.toByteArray();
base64 = Base64.encodeToString(input, Base64.DEFAULT);
//LocalProfileActivity.input = input;
}catch(Exception e){
Log.e(LOG_TAG,"[ONACTIVITYRESULT] Could not bind input to the bytearray: " + e.getMessage());
}
}
catch (Exception e){
Log.e("LocalProfile", "ConvertandSetImagetoBase64: Could not load selected profile image");
}
return base64;
}
public String getStringFromBuffer(InputStreamReader inputstrread){
BufferedReader bRead = new BufferedReader(inputstrread);
String line = null;
StringBuffer jsonText = new StringBuffer();
try {
while((line=bRead.readLine())!=null){
jsonText.append(line);
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return jsonText.toString();
}
public String ConvertByteArrayToString(byte[] b) {
// byte[] to string
String input = new String(b);
return input;
}
public byte[] ConvertStringToByteArray(String str) {
// string to byte[]
byte[] bytes = str.getBytes();
return bytes;
}
public static byte[] getBytesFromInputStream(InputStream is)
throws IOException {
// Get the size of the file
long length = is.available();
if (length > Integer.MAX_VALUE) {
// File is too large
}
// Create the byte array to hold the data
byte[] bytes = new byte[(int) length];
// Read in the bytes
int offset = 0;
int numRead = 0;
while (offset < bytes.length
&& (numRead = is.read(bytes, offset, bytes.length - offset)) >= 0) {
offset += numRead;
}
// Ensure all the bytes have been read in
if (offset < bytes.length) {
throw new IOException("Could not completely stream ");
}
// Close the input stream and return bytes
is.close();
return bytes;
}
public static String writeFile(Bitmap finalBitmap) {
String filePath = "";
String root = Environment.getExternalStorageDirectory().toString();
File myDir = new File(root + "/saved_images");
myDir.mkdirs();
Random generator = new Random();
int n = 10000;
n = generator.nextInt(n);
String fname = "Image-"+ n +".jpg";
File file = new File (myDir, fname);
if (file.exists ()) file.delete ();
try {
FileOutputStream outFile = new FileOutputStream(file);
finalBitmap.compress(Bitmap.CompressFormat.JPEG, 90, outFile);
outFile.flush();
outFile.close();
} catch (Exception e) {
e.printStackTrace();
}
filePath = root+"/saved_images/"+fname;
return filePath;
}
public class RepeatingThread implements Runnable {
private final Handler mHandler = new Handler();
private int len = 0;
private byte[] input = new byte[len];
public RepeatingThread() {
//try {
Log.e(LOG_TAG, "Before inputJSON String");
//inputJSON = dataInputStream.readUTF();
//URL url = new URL("tcp://23.23.175.213:1337");
//inputJSON = dataInputStream.readUTF();
//inputstrrd = new InputStreamReader(socket.getInputStream());
String hello = "hello world";
//String inputJSON = getStringFromBuffer(new InputStreamReader(socket.getInputStream()));
//Convert
Log.e(LOG_TAG, "After inputJSON String:" + inputJSON);
/*}
catch (UnknownHostException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}*/
//LOOK HERE FIRST
//inputJSON is what is received back from the server - Take the inputJSON
//String and use regular expressions HERE to remove all the other characters in the
//string except the payload JSON.
//refreshViewModels(inputJSON);
}
@Override
public void run() {
try {
//outputstrwr.write(outputJSONserv); //UNCOMMENT IF NEED TO SEND DATA TO GET JSON BACK
inputJSON = ConvertByteArrayToString(getBytesFromInputStream(inputStr));
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Log.e(LOG_TAG, "IN REPEATINGTHREAD-INPUTJSON:" + inputJSON);
refreshViewModels(inputJSON);
mHandler.postDelayed(this, 3000);
}
}
public void refreshViewModels(String inputJSON) {
try {
ListView servicesListView = (ListView) this
.findViewById(R.id.profilesListView);
String[] from = new String[] { "profilePic", "neighborName",
"tagLine" };
int[] to = new int[] { R.id.avatar, R.id.username, R.id.email };
// prepare the list of all records
List<HashMap<String, Object>> fillMaps = new ArrayList<HashMap<String, Object>>();
List<Profile> profiles = new ArrayList<Profile>();
// Clear the position mapping list and reset it
this.posMap.clear();
Log.i(LOG_TAG, "NEW inputJSON: " + inputJSON);
inputJSON = getPayloadStr(inputJSON);
Log.i(LOG_TAG, "NEW inputJSON2: " + inputJSON);
JSONArray profileArray = new JSONArray(inputJSON);
for (int i=0; i<profileArray.length(); i++) {
JSONObject jsonObject = profileArray.getJSONObject(i);
Gson gson = new Gson();
Profile p = gson.fromJson(gson.toJson(jsonObject).toString(), Profile.class);
profiles.add(p);
}
int pos = 0;
// Creates the fillMaps list for the listAdapter
Log.i(LOG_TAG, "Profiles size: " + profiles.size());
//showToast("Profiles size: " + profiles.size());
for (Profile p : profiles) {
// Create mapping for list adapter
HashMap<String, Object> map = new HashMap<String, Object>();
map.put("profilePic",
p.getAttributeValue("photo")== null? "Not Set" : p
.getAttributeValue("photo"));
map.put("neighborName",
p.getAttributeValue("Name") == null? "Not Set" : p
.getAttributeValue("Name"));
map.put("tagLine",
p.getAttributeValue("TagLine") == null? "Not Set" : p
.getAttributeValue("TagLine"));
fillMaps.add(map);
// Reset the postion mapping
this.posMap.put(pos++, p);
}
ListAdapter servicesListAdapter = new myAdapter(this, fillMaps,
R.layout.listitem, from, to);
servicesListView.setAdapter(servicesListAdapter);
} catch (Exception e) {
Log.e(LOG_TAG, "Error making list adapter: " + e.getMessage());
}
}
public String getPayloadStr(String profileString) {
Log.e("LOG_TAG", "Profile Str:"+profileString);
Pattern pattern = Pattern.compile(".*?payload\":(.*)\\}");
Log.e("LOG_TAG", "I got here 1");
Matcher matcher = pattern.matcher(profileString);
Log.e("LOG_TAG", "I got here 12");
//Matcher m = responseCodePattern.matcher(firstHeader);
matcher.matches();
matcher.groupCount();
//matcher.group(0);
Log.e("LOG_TAG", "I got here 2"+matcher.group(1));
return matcher.group(1);
}
private class myAdapter extends SimpleAdapter {
public myAdapter(Context context, List<? extends Map<String, ?>> data,
int resource, String[] from, int[] to) {
super(context, data, resource, from, to);
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
if (convertView == null) {
convertView = getLayoutInflater().inflate(R.layout.listitem,
null);
}
HashMap<String, Object> data = (HashMap<String, Object>) getItem(position);
((TextView) convertView.findViewById(R.id.username))
.setText((String) data.get("neighborName"));
((TextView) convertView.findViewById(R.id.email))
.setText((String) data.get("tagLine"));
// Convert a string representing an image back to an image
String base64 = ((String)data.get("profilePic"));
byte[] picBytes = Base64.decode(base64, Base64.DEFAULT);
Bitmap bitmap = BitmapFactory.decodeByteArray(picBytes, 0, picBytes.length);
//THE IF AND THE ELSE NEED TO BE SWITCHED
if (bitmap==null){
((ImageView) convertView.findViewById(R.id.avatar)).setImageResource(R.drawable.btn_whooznear);
}else{
((ImageView) convertView.findViewById(R.id.avatar)).setImageBitmap(bitmap);
}
return convertView;
}
}
public void callProfileActivity(int position)
{
// Catch the case when service info is empty
if(serviceInfoList.size()==0){
return;
}
Profile profClick = posMap.get(position);
String b64Str = profClick.getAttributeValue("photo");
Intent startViewActivity = new Intent();
startViewActivity.putExtra("TransProfile", (Profile)posMap.get(position));
startViewActivity.putExtra("PhotoBase64", b64Str);
if(serviceInfoList.size()>position){
//DO SOMETHING HERE
}else{
Log.e(LOG_TAG,"Profile doesn't exist in sevice infoList? Selecting first one");
}
startViewActivity.setClass(this, ViewProfileActivity.class);
startActivity(startViewActivity);
}
/**
* Initialize the event handlers
*/
public void initEventHandlers() {
// Service List View
ListView servicesListView = (ListView) this
.findViewById(R.id.profilesListView);
servicesListView
.setOnItemClickListener(new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView<?> arg0, View v,
int position, long id) {
Profile clickedProfile = posMap.get(position);
//showToast("Clicked Pos: " + position);
/*Intent intent = new Intent(ConnectActivity.this, ViewProfileActivity.class);
intent.putExtra("ClickProfile", posMap.get(position));*/
callProfileActivity(position);
}
});
}
/*@Override
public void onBackPressed() { // do something on back.
super.onBackPressed();
Intent myIntent = new Intent(AndroidClient.this, ProfileActivity.class);
startActivity(myIntent);
return;
}*/
}
最佳答案
你的代码相当长,所以我不能确定到底是什么问题,但这里肯定有问题:
public static byte[] getBytesFromInputStream(InputStream is)
throws IOException {
// Get the size of the file
long length = is.available();
如果您在发送 URL 请求后立即调用此函数,服务器可能没有时间发回结果,因此 is.available()
可能会返回零或另一个小于您希望可用的实际字节数。试试code like this用于读取文件。
关于java - Android - 输入流无法正常工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12135399/
我正在编写一个具有以下签名的 Java 方法。 void Logger(Method method, Object[] args); 如果一个方法(例如 ABC() )调用此方法 Logger,它应该
我是 Java 新手。 我的问题是我的 Java 程序找不到我试图用作的图像文件一个 JButton。 (目前这段代码什么也没做,因为我只是得到了想要的外观第一的)。这是我的主课 代码: packag
好的,今天我在接受采访,我已经编写 Java 代码多年了。采访中说“Java 垃圾收集是一个棘手的问题,我有几个 friend 一直在努力弄清楚。你在这方面做得怎么样?”。她是想骗我吗?还是我的一生都
我的 friend 给了我一个谜语让我解开。它是这样的: There are 100 people. Each one of them, in his turn, does the following
如果我将使用 Java 5 代码的应用程序编译成字节码,生成的 .class 文件是否能够在 Java 1.4 下运行? 如果后者可以工作并且我正在尝试在我的 Java 1.4 应用程序中使用 Jav
有关于why Java doesn't support unsigned types的问题以及一些关于处理无符号类型的问题。我做了一些搜索,似乎 Scala 也不支持无符号数据类型。限制是Java和S
我只是想知道在一个 java 版本中生成的字节码是否可以在其他 java 版本上运行 最佳答案 通常,字节码无需修改即可在 较新 版本的 Java 上运行。它不会在旧版本上运行,除非您使用特殊参数 (
我有一个关于在命令提示符下执行 java 程序的基本问题。 在某些机器上我们需要指定 -cp 。 (类路径)同时执行java程序 (test为java文件名与.class文件存在于同一目录下) jav
我已经阅读 StackOverflow 有一段时间了,现在我才鼓起勇气提出问题。我今年 20 岁,目前在我的家乡(罗马尼亚克卢日-纳波卡)就读 IT 大学。足以介绍:D。 基本上,我有一家提供簿记应用
我有 public JSONObject parseXML(String xml) { JSONObject jsonObject = XML.toJSONObject(xml); r
我已经在 Java 中实现了带有动态类型的简单解释语言。不幸的是我遇到了以下问题。测试时如下代码: def main() { def ks = Map[[1, 2]].keySet()
一直提示输入 1 到 10 的数字 - 结果应将 st、rd、th 和 nd 添加到数字中。编写一个程序,提示用户输入 1 到 10 之间的任意整数,然后以序数形式显示该整数并附加后缀。 public
我有这个 DownloadFile.java 并按预期下载该文件: import java.io.*; import java.net.URL; public class DownloadFile {
我想在 GUI 上添加延迟。我放置了 2 个 for 循环,然后重新绘制了一个标签,但这 2 个 for 循环一个接一个地执行,并且标签被重新绘制到最后一个。 我能做什么? for(int i=0;
我正在对对象 Student 的列表项进行一些测试,但是我更喜欢在 java 类对象中创建硬编码列表,然后从那里提取数据,而不是连接到数据库并在结果集中选择记录。然而,自从我这样做以来已经很长时间了,
我知道对象创建分为三个部分: 声明 实例化 初始化 classA{} classB extends classA{} classA obj = new classB(1,1); 实例化 它必须使用
我有兴趣使用 GPRS 构建车辆跟踪系统。但是,我有一些问题要问以前做过此操作的人: GPRS 是最好的技术吗?人们意识到任何问题吗? 我计划使用 Java/Java EE - 有更好的技术吗? 如果
我可以通过递归方法反转数组,例如:数组={1,2,3,4,5} 数组结果={5,4,3,2,1}但我的结果是相同的数组,我不知道为什么,请帮助我。 public class Recursion { p
有这样的标准方式吗? 包括 Java源代码-测试代码- Ant 或 Maven联合单元持续集成(可能是巡航控制)ClearCase 版本控制工具部署到应用服务器 最后我希望有一个自动构建和集成环境。
我什至不知道这是否可能,我非常怀疑它是否可能,但如果可以,您能告诉我怎么做吗?我只是想知道如何从打印机打印一些文本。 有什么想法吗? 最佳答案 这里有更简单的事情。 import javax.swin
我是一名优秀的程序员,十分优秀!