我一直在尝试编写一个应用程序,将图像发送到另一个Android设备一段时间了,而我却失败了。我在服务器端什么都没得到。以下是我的客户代码,请你帮我弄清楚我哪里出错了。
import java.io.BufferedWriter;
import java.io.ByteArrayOutputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.PrintStream;
import java.io.PrintWriter;
import java.net.InetAddress;
import java.net.Socket;
import java.net.UnknownHostException;
import java.nio.ByteBuffer;
import android.app.Activity;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Bitmap.CompressFormat;
import android.graphics.drawable.BitmapDrawable;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.provider.Settings;
import android.util.DisplayMetrics;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import com.google.android.gms.appindexing.Action;
import com.google.android.gms.appindexing.AppIndex;
import com.google.android.gms.appindexing.Thing;
import com.google.android.gms.common.api.GoogleApiClient;
public class ClientLate extends Activity {
private static final int SERVERPORT = 8080;
private static final int SELECT_PICTURE = 1;
ImageView imageView;
Button send;
Bitmap bmp;
private Socket socket;
private String selectedImagePath;
private ImageView img;
private static final String SERVER_IP = "192.168.111.11";
/**
* ATTENTION: This was auto-generated to implement the App Indexing API.
* See https://g.co/AppIndexing/AndroidStudio for more information.
*/
private GoogleApiClient client;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_client_late);
imageView = (ImageView) findViewById(R.id.imageView1);
send = (Button)findViewById(R.id.bSend);
new Thread(new ClientThread()).start();
// ATTENTION: This was auto-generated to implement the App Indexing API.
// See https://g.co/AppIndexing/AndroidStudio for more information.
client = new GoogleApiClient.Builder(this).addApi(AppIndex.API).build();
}
public void onBrowseClick(View v) {
Button imagePick = (Button) findViewById(R.id.bBrowse);
//pick image from the gallery
//Intent picPickerIntent = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent, "Select Picture"), SELECT_PICTURE);
//start an activity and tell it we want a result
//startActivityForResult(Intent.createChooser(intent, "Select Picture"), SELECT_PICTURE);
//tvServerMsg.setText(String.valueOf(imageUpload.getTag()));
}
public void onSend(View view) {
//ImageView imageView2 = (ImageView) findViewById(R.id.imageView2);
bmp = ((BitmapDrawable) imageView.getDrawable()).getBitmap();
//Bitmap btmp = Bitmap.create(imageView.getBitmap());
//imageView2.setImageBitmap(bmp);
ByteArrayOutputStream bos = new ByteArrayOutputStream();
bmp.compress(CompressFormat.PNG, 0 /*ignored for PNG*/, bos);
byte[] array = bos.toByteArray();
try {
OutputStream out = socket.getOutputStream();
DataOutputStream dos = new DataOutputStream(out);
dos.writeInt(array.length);
dos.write(array, 0, array.length);
} catch (UnknownHostException e) {
System.out.printf("Problem 1");
e.printStackTrace();
} catch (IOException e) {
System.out.printf("Problem 2");
e.printStackTrace();
} catch (Exception e) {
System.out.printf("Problem 3");
e.printStackTrace();
}
}
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == RESULT_OK) {
if (requestCode == SELECT_PICTURE) {
Uri selectedImageUri = data.getData();
selectedImagePath = getPath(selectedImageUri);
TextView path = (TextView) findViewById(R.id.tvPath);
path.setText("Image Path : " + selectedImagePath);
imageView.setImageURI(selectedImageUri);
}
}
}
public void selectPic(View view) {
try {
//EditText et = (EditText) findViewById(R.id.EditText01);
Bitmap bmp = ((BitmapDrawable) imageView.getDrawable()).getBitmap();
//String str = et.getText().toString();
Button bBrowse = ((Button) findViewById(R.id.bBrowse));
bBrowse.setOnClickListener(new View.OnClickListener() {
public void onClick(View arg0) {
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent, "Select Picture"), SELECT_PICTURE);
}
});
ByteArrayOutputStream bos = new ByteArrayOutputStream();
bmp.compress(CompressFormat.PNG, 0 /*ignored for PNG*/, bos);
byte[] array = bos.toByteArray();
OutputStream out = socket.getOutputStream();
DataOutputStream dos = new DataOutputStream(out);
dos.writeInt(array.length);
dos.write(array, 0, array.length);
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* ATTENTION: This was auto-generated to implement the App Indexing API.
* See https://g.co/AppIndexing/AndroidStudio for more information.
*/
public Action getIndexApiAction() {
Thing object = new Thing.Builder().setName("ClientLate Page") // TODO: Define a title for the content shown.
// TODO: Make sure this auto-generated URL is correct.
.setUrl(Uri.parse("http://[ENTER-YOUR-URL-HERE]")).build();
return new Action.Builder(Action.TYPE_VIEW).setObject(object).setActionStatus(Action.STATUS_TYPE_COMPLETED).build();
}
@Override
public void onStart() {
super.onStart();
// ATTENTION: This was auto-generated to implement the App Indexing API.
// See https://g.co/AppIndexing/AndroidStudio for more information.
client.connect();
AppIndex.AppIndexApi.start(client, getIndexApiAction());
}
@Override
public void onStop() {
super.onStop();
// ATTENTION: This was auto-generated to implement the App Indexing API.
// See https://g.co/AppIndexing/AndroidStudio for more information.
AppIndex.AppIndexApi.end(client, getIndexApiAction());
client.disconnect();
}
class ClientThread implements Runnable {
@Override
public void run() {
try {
InetAddress serverAddr = InetAddress.getByName(SERVER_IP);
socket = new Socket("192.168.111.11", 8080);
} catch (UnknownHostException e1) {
e1.printStackTrace();
} catch (IOException e1) {
e1.printStackTrace();
}
}
}
public String getPath(Uri uri) {
String[] projection = {MediaStore.Images.Media.DATA};
Cursor cursor = getContentResolver().query(uri, projection, null, null, null);
int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
return cursor.getString(column_index);
}
}
清单文件
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.melo.myapplication">
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity android:name=".ClientLate">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity><!-- ATTENTION: This was auto-generated to add Google Play services to your project for
App Indexing. See https://g.co/AppIndexing/AndroidStudio for more information. -->
<meta-data
android:name="com.google.android.gms.version"
android:value="@integer/google_play_services_version" />
</application>
</manifest>
XML文件
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/activity_client_late"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context="com.example.melo.myapplication.ClientLate">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<Button
android:id="@+id/bBrowse"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Browse"
android:onClick="onBrowseClick"/>
<Button
android:id="@+id/bSend"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Send"
android:onClick="onSend"/>
<TextView
android:id="@+id/tvPath"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
<ImageView
android:id="@+id/imageView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<ImageView
android:id="@+id/imageView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</LinearLayout>
</RelativeLayout>
我的日志。
D/dalvikvm: GC_FOR_ALLOC freed 757K, 14% free 14096K/16387K, paused 15ms, total 15ms
W/System.err: java.lang.NullPointerException
W/System.err: at com.example.melo.myapplication.ClientLate.onSend(ClientLate.java:104)
W/System.err: at java.lang.reflect.Method.invokeNative(Native Method)
W/System.err: at java.lang.reflect.Method.invoke(Method.java:511)
W/System.err: at android.view.View$1.onClick(View.java:3598)
W/System.err: at android.view.View.performClick(View.java:4103)
W/System.err: at android.view.View$PerformClick.run(View.java:17117)
W/System.err: at android.os.Handler.handleCallback(Handler.java:615)
W/System.err: at android.os.Handler.dispatchMessage(Handler.java:92)
W/System.err: at android.os.Looper.loop(Looper.java:137)
W/System.err: at android.app.ActivityThread.main(ActivityThread.java:4744)
W/System.err: at java.lang.reflect.Method.invokeNative(Native Method)
W/System.err: at java.lang.reflect.Method.invoke(Method.java:511)
W/System.err: at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:786)
W/System.err: at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
W/System.err: at dalvik.system.NativeStart.main(Native Method)
答案 0 :(得分:0)
尝试改变
OutputStream out = socket.getOutputStream(); DataOutputStream dos = new DataOutputStream(out); dos.writeInt(array.length); dos.write(array, 0, array.length);
到:
OutputStream output = socket.getOutputStream(); output.write(array, 0, array.length);; output.flush();