我目前正在开发Java编码技能,并创建了以下代码以通过HTTP协议将我的应用程序连接到互联网,并从我的网站上捕获一个.php脚本。
package com.example.markmakarovskiy.myapplication;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
public class MainActivity extends AppCompatActivity {
private static String LOG_TAG = "MainActivity";
TextView TxtResult;
Button PostBtn, GetBtn;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
GetBtn = (Button) findViewById(R.id.get_btn);
PostBtn = (Button) findViewById(R.id.post_btn);
GetBtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
new MakeNetworkCall().execute("http://futurama.club/android.php?get=1", "Get");
}
});
PostBtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
new MakeNetworkCall().execute("http://futurama.club/android.php?post=1", "Post");
}
});
}
InputStream ByGetMethod(String ServerURL) {
InputStream DataInputStream = null;
try {
URL url = new URL(ServerURL);
HttpURLConnection cc = (HttpURLConnection)
url.openConnection();
//set timeout for reading InputStream
cc.setReadTimeout(5000);
// set timeout for connection
cc.setConnectTimeout(5000);
//set HTTP method to GET
cc.setRequestMethod("GET");
//set it to true as we are connecting for input
cc.setDoInput(true);
//reading HTTP response code
int response = cc.getResponseCode();
//if response code is 200 / OK then read Inputstream
if (response == HttpURLConnection.HTTP_OK) {
DataInputStream = cc.getInputStream();
}
} catch (Exception e) {
Log.e(LOG_TAG, "Error in GetData", e);
}
return DataInputStream;
}
InputStream ByPostMethod(String ServerURL) {
InputStream DataInputStream = null;
try {
//Post parameters
String PostParam = "first_name=Mark&last_name=Ardman";
//Preparing
URL url = new URL(ServerURL);
HttpURLConnection cc = (HttpURLConnection)
url.openConnection();
//set timeout for reading InputStream
cc.setReadTimeout(5000);
// set timeout for connection
cc.setConnectTimeout(5000);
//set HTTP method to POST
cc.setRequestMethod("POST");
//set it to true as we are connecting for input
cc.setDoInput(true);
//opens the communication link
cc.connect();
//Writing data (bytes) to the data output stream
DataOutputStream dos = new DataOutputStream(cc.getOutputStream());
dos.writeBytes(PostParam);
//flushes data output stream.
dos.flush();
dos.close();
//Getting HTTP response code
int response = cc.getResponseCode();
//if response code is 200 / OK then read Inputstream
//HttpURLConnection.HTTP_OK is equal to 200
if(response == HttpURLConnection.HTTP_OK) {
DataInputStream = cc.getInputStream();
}
} catch (Exception e) {
Log.e(LOG_TAG, "Error in GetData", e);
}
return DataInputStream;
}
String ConvertStreamToString(InputStream stream) {
InputStreamReader isr = new InputStreamReader(stream);
BufferedReader reader = new BufferedReader(isr);
StringBuilder response = new StringBuilder();
String line = null;
try {
while ((line = reader.readLine()) != null) {
response.append(line);
}
} catch (IOException e) {
Log.e(LOG_TAG, "Error in ConvertStreamToString", e);
} catch (Exception e) {
Log.e(LOG_TAG, "Error in ConvertStreamToString", e);
} finally {
try {
stream.close();
} catch (IOException e) {
Log.e(LOG_TAG, "Error in ConvertStreamToString", e);
} catch (Exception e) {
Log.e(LOG_TAG, "Error in ConvertStreamToString", e);
}
}
return response.toString();
}
public void DisplayMessage(String a) {
TxtResult = (TextView) findViewById(R.id.response);
TxtResult.setText(a);
}
private class MakeNetworkCall extends AsyncTask<String, Void, String> {
@Override
protected void onPreExecute() {
super.onPreExecute();
DisplayMessage("Please Wait ...");
}
@Override
protected String doInBackground(String... arg) {
InputStream is = null;
String URL = arg[0];
Log.d(LOG_TAG, "URL: " + URL);
String res = "";
if (arg[1].equals("Post")) {
is = ByPostMethod(URL);
} else {
is = ByGetMethod(URL);
}
if (is != null) {
res = ConvertStreamToString(is);
} else {
res = "Something went wrong";
}
return res;
}
protected void onPostExecute(String result) {
super.onPostExecute(result);
DisplayMessage(result);
Log.d(LOG_TAG, "Result: " + result);
}
}
}
这是我的MainActivity.java。它应该调用php脚本并加载两个变量之一(取决于您按下的按钮)。但是问题是我的应用程序启动时崩溃了。怎么修? XD
以防万一,这是我的.xml文件
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.example.markmakarovskiy.myapplication.MainActivity">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:orientation="vertical">
<Button
android:id="@+id/get_btn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:padding="15dp"
android:text="@string/button"
android:textSize="16sp" />
<Button
android:id="@+id/post_btn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:padding="15dp"
android:text="@string/post_method"
android:textSize="16sp" />
<TextView
android:id="@+id/response"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="30sp" />
</LinearLayout>
</android.support.constraint.ConstraintLayout>
编辑-崩溃报告
08/05 13:53:19: Launching app
$ adb install-multiple -r -t C:\Users\Mark Makarovskiy\AndroidStudioProjects\MyApplication2\app\build\intermediates\resources\instant-run\debug\resources-debug.apk C:\Users\Mark Makarovskiy\AndroidStudioProjects\MyApplication2\app\build\intermediates\split-apk\debug\slices\slice_6.apk C:\Users\Mark Makarovskiy\AndroidStudioProjects\MyApplication2\app\build\intermediates\split-apk\debug\slices\slice_5.apk C:\Users\Mark Makarovskiy\AndroidStudioProjects\MyApplication2\app\build\intermediates\split-apk\debug\slices\slice_7.apk C:\Users\Mark Makarovskiy\AndroidStudioProjects\MyApplication2\app\build\intermediates\split-apk\debug\slices\slice_9.apk C:\Users\Mark Makarovskiy\AndroidStudioProjects\MyApplication2\app\build\intermediates\split-apk\debug\slices\slice_8.apk C:\Users\Mark Makarovskiy\AndroidStudioProjects\MyApplication2\app\build\intermediates\split-apk\debug\slices\slice_3.apk C:\Users\Mark Makarovskiy\AndroidStudioProjects\MyApplication2\app\build\intermediates\split-apk\debug\dep\dependencies.apk C:\Users\Mark Makarovskiy\AndroidStudioProjects\MyApplication2\app\build\intermediates\split-apk\debug\slices\slice_4.apk C:\Users\Mark Makarovskiy\AndroidStudioProjects\MyApplication2\app\build\intermediates\split-apk\debug\slices\slice_2.apk C:\Users\Mark Makarovskiy\AndroidStudioProjects\MyApplication2\app\build\intermediates\split-apk\debug\slices\slice_1.apk C:\Users\Mark Makarovskiy\AndroidStudioProjects\MyApplication2\app\build\intermediates\split-apk\debug\slices\slice_0.apk C:\Users\Mark Makarovskiy\AndroidStudioProjects\MyApplication2\app\build\intermediates\instant-run-apk\debug\app-debug.apk
Split APKs installed
$ adb shell am start -n "com.example.markmakarovskiy.myapplication/com.example.markmakarovskiy.myapplication.MainActivity" -a android.intent.action.MAIN -c android.intent.category.LAUNCHER
Client not ready yet..Waiting for process to come online
Connected to process 25936 on device emulator-5554
Capturing and displaying logcat messages from application. This behavior can be disabled in the "Logcat output" section of the "Debugger" settings page.
W/y.myapplicatio: JIT profile information will not be recorded: profile file does not exits.
I/chatty: uid=10008(com.example.markmakarovskiy.myapplication) identical 10 lines
W/y.myapplicatio: JIT profile information will not be recorded: profile file does not exits.
I/InstantRun: starting instant run server: is main process
W/y.myapplicatio: JNI critical lock held for 19.291ms on Thread[1,tid=25936,Runnable,Thread*=0xe69da000,peer=0x73e171f0,"main"]
I/y.myapplicatio: Background concurrent copying GC freed 12750(2MB) AllocSpace objects, 0(0B) LOS objects, 54% free, 1268KB/2MB, paused 38.531ms total 657.847ms
W/y.myapplicatio: Accessing hidden method Landroid/view/View;->computeFitSystemWindows(Landroid/graphics/Rect;Landroid/graphics/Rect;)Z (light greylist, reflection)
W/y.myapplicatio: Accessing hidden method Landroid/view/ViewGroup;->makeOptionalFitsSystemWindows()V (light greylist, reflection)
W/y.myapplicatio: JNI critical lock held for 20.808ms on Thread[1,tid=25936,Runnable,Thread*=0xe69da000,peer=0x73e171f0,"main"]
D/AndroidRuntime: Shutting down VM
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.markmakarovskiy.myapplication, PID: 25936
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.markmakarovskiy.myapplication/com.example.markmakarovskiy.myapplication.MainActivity}: android.view.InflateException: Binary XML file line #9: Binary XML file line #9: Error inflating class <unknown>
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2902)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3037)
at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:78)
at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:108)
at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:68)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1797)
at android.os.Handler.dispatchMessage(Handler.java:106)
at android.os.Looper.loop(Looper.java:193)
at android.app.ActivityThread.main(ActivityThread.java:6642)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:493)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:858)
Caused by: android.view.InflateException: Binary XML file line #9: Binary XML file line #9: Error inflating class <unknown>
Caused by: android.view.InflateException: Binary XML file line #9: Error inflating class <unknown>
Caused by: java.lang.reflect.InvocationTargetException
at java.lang.reflect.Constructor.newInstance0(Native Method)
at java.lang.reflect.Constructor.newInstance(Constructor.java:343)
at android.view.LayoutInflater.createView(LayoutInflater.java:647)
at com.android.internal.policy.PhoneLayoutInflater.onCreateView(PhoneLayoutInflater.java:58)
at android.view.LayoutInflater.onCreateView(LayoutInflater.java:720)
at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:788)
at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:730)
at android.view.LayoutInflater.rInflate(LayoutInflater.java:863)
at android.view.LayoutInflater.rInflateChildren(LayoutInflater.java:824)
at android.view.LayoutInflater.inflate(LayoutInflater.java:515)
at android.view.LayoutInflater.inflate(LayoutInflater.java:423)
at android.view.LayoutInflater.inflate(LayoutInflater.java:374)
at android.support.v7.app.AppCompatDelegateImplV9.setContentView(AppCompatDelegateImplV9.java:287)
at android.support.v7.app.AppCompatActivity.setContentView(AppCompatActivity.java:139)
at com.example.markmakarovskiy.myapplication.MainActivity.onCreate(MainActivity.java:27)
at android.app.Activity.performCreate(Activity.java:7131)
at android.app.Activity.performCreate(Activity.java:7122)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1271)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2882)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3037)
at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:78)
at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:108)
at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:68)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1797)
at android.os.Handler.dispatchMessage(Handler.java:106)
at android.os.Looper.loop(Looper.java:193)
at android.app.ActivityThread.main(ActivityThread.java:6642)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:493)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:858)
Caused by: java.lang.UnsupportedOperationException: Can't convert value at index 15 to dimension: type=0x4
at android.content.res.TypedArray.getDimensionPixelSize(TypedArray.java:736)
at android.view.View.<init>(View.java:5030)
at android.view.ViewGroup.<init>(ViewGroup.java:659)
E/AndroidRuntime: at android.widget.LinearLayout.<init>(LinearLayout.java:244)
at android.widget.LinearLayout.<init>(LinearLayout.java:240)
at android.widget.LinearLayout.<init>(LinearLayout.java:236)
... 30 more
I/Process: Sending signal. PID: 25936 SIG: 9
Application terminated.
答案 0 :(得分:0)
日志读取Can't convert value at index 15 to dimension
...,这暗示您某个地方有一个随机值,而不是适当的维度,例如。 24dp
或24sp
作为该XML布局中的值,不能被夸大。