Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/android/233.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Android 首次使用okhttp崩溃_Android_Okhttp - Fatal编程技术网

Android 首次使用okhttp崩溃

Android 首次使用okhttp崩溃,android,okhttp,Android,Okhttp,我正在用示例尝试okHttp 但是我有这个错误。。检查以下日志 09-23 09:29:29.566 13750-13750/com.justedhak.www.test E/AndroidRuntime﹕ FATAL EXCEPTION: main java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{com.justedhak.www.test/com.justedhak.www.test.

我正在用示例尝试okHttp 但是我有这个错误。。检查以下日志

09-23 09:29:29.566  13750-13750/com.justedhak.www.test E/AndroidRuntime﹕ FATAL EXCEPTION: main
    java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{com.justedhak.www.test/com.justedhak.www.test.MainActivity}: java.lang.ClassCastException: com.justedhak.www.test.MainActivity cannot be cast to android.app.Activity
            at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1983)
            at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2084)
            at android.app.ActivityThread.access$600(ActivityThread.java:130)
            at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1195)
            at android.os.Handler.dispatchMessage(Handler.java:99)
            at android.os.Looper.loop(Looper.java:137)
            at android.app.ActivityThread.main(ActivityThread.java:4745)
            at java.lang.reflect.Method.invokeNative(Native Method)
            at java.lang.reflect.Method.invoke(Method.java:511)
            at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:786)
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
            at dalvik.system.NativeStart.main(Native Method)
     Caused by: java.lang.ClassCastException: com.justedhak.www.test.MainActivity cannot be cast to android.app.Activity
            at android.app.Instrumentation.newActivity(Instrumentation.java:1053)
            at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1974)
            at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2084)
            at android.app.ActivityThread.access$600(ActivityThread.java:130)
            at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1195)
            at android.os.Handler.dispatchMessage(Handler.java:99)
            at android.os.Looper.loop(Looper.java:137)
            at android.app.ActivityThread.main(ActivityThread.java:4745)
            at java.lang.reflect.Method.invokeNative(Native Method)
这是显而易见的

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.justedhak.www.test" >

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name=".MainActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>
编辑

package com.example.justedhak;
导入java.io.ByteArrayOutputStream;
导入java.io.FileNotFoundException;
导入java.io.IOException;
导入java.io.InputStream;
导入java.util.ArrayList;
导入java.util.Calendar;
导入org.apache.http.HttpResponse;
导入org.apache.http.NameValuePair;
导入org.apache.http.client.HttpClient;
导入org.apache.http.client.entity.UrlEncodedFormEntity;
导入org.apache.http.client.methods.HttpPost;
导入org.apache.http.impl.client.DefaultHttpClient;
导入org.apache.http.message.BasicNameValuePair;
导入android.app.Activity;
导入android.content.Intent;
导入android.graphics.Bitmap;
导入android.graphics.BitmapFactory;
导入android.net.Uri;
导入android.os.Bundle;
导入android.view.view;
导入android.widget.ArrayAdapter;
导入android.widget.EditText;
导入android.widget.ImageView;
导入android.widget.Spinner;
导入android.widget.Toast;
公共类AddImage扩展活动{
输入流输入流;
字符串分类;
字符串标题;
//私有位图bmp;
图像视图图像视图;
@凌驾
创建公共空间(捆绑冰柱){
超级冰柱;
setContentView(R.layout.main);
//获取价值
EditText CaptionTXT=(EditText)findViewById(R.id.caption);
caption=captionTXT.getText().toString();
//纺纱机
微调器下拉列表=(微调器)findViewById(R.id.spinner1);
字符串[]项=新字符串[]{“黎巴嫩笑话”、“学生笑话”、“引号”};
ArrayAdapter=新的ArrayAdapter(这个,android.R.layout.simple\u微调器\u项,项);
下拉列表.setAdapter(适配器);
categorie=dropdown.getSelectedItem().toString();
imageview=(imageview)findViewById(R.id.imageview);
Intent=getIntent();
字符串selectedImage=intent.getStringExtra(“图像路径”);
urifileuri=Uri.parse(selectedImage);
InputStream imageStream=null;
试一试{
imageStream=getContentResolver().openInputStream(fileUri);
}catch(filenotfounde异常){
e、 printStackTrace();
}
位图bmp=BitmapFactory.decodeStream(imageStream);
ByteArrayOutputStream=新建ByteArrayOutputStream();
bmp.compress(Bitmap.CompressFormat.JPEG,30,流);
byte[]byteArray=stream.toByteArray();
位图位图=位图工厂.decodeByteArray(byteArray,0,byteArray.length);
设置图像位图(位图);
}
公共void onclick(视图)
{
Toast.makeText(AddImage.this,“上传图像”,Toast.LENGTH_LONG.show();
上传();
意向i=新意向(本,
主要活动(课堂);
星触觉(i);
}
公开作废上载()
{
Calendar thisCal=Calendar.getInstance();
thisCal.getTimeInMillis();
//android.util.Log.i(“时间类”,“以毫秒为单位的时间值”+thisCal);
//位图Bitmap=BitmapFactory.decodeResource(getResources(),R.drawable.ic_启动器);
//ByteArrayOutputStream=新建ByteArrayOutputStream();
//bmp.compress(Bitmap.CompressFormat.PNG,90,stream);//压缩为所需格式。
//重新创建
Intent=getIntent();
字符串selectedImage=intent.getStringExtra(“图像路径”);
urifileuri=Uri.parse(selectedImage);
System.out.println(fileUri);
InputStream imageStream=null;
试一试{
imageStream=getContentResolver().openInputStream(fileUri);
}catch(filenotfounde异常){
e、 printStackTrace();
}
位图bmp=BitmapFactory.decodeStream(imageStream);
ByteArrayOutputStream=新建ByteArrayOutputStream();
bmp.compress(Bitmap.CompressFormat.JPEG,30,流);
byte[]byteArray=stream.toByteArray();
位图位图=位图工厂.decodeByteArray(byteArray,0,byteArray.length);
设置图像位图(位图);
int width=bitmap.getWidth();
int height=bitmap.getHeight();
系统输出打印长度(宽度);
系统输出打印LN(高度);
getResizedBitmap(位图,200);
试一试{
stream.close();
流=空;
}捕获(IOE异常){
e、 printStackTrace();
}
字符串image_str=Base64.encodeBytes(byteArray);
最终ArrayList nameValuePairs=新ArrayList();
添加(新的BasicNameValuePair(“image”,image_str));
添加(新的BasicNameValuePair(“标题”,标题));
添加(新的BasicNameValuePair(“名称”、“je”));
添加(新的BasicNameValuePair(“分类”,分类));
线程t=新线程(新的可运行线程(){
@凌驾
公开募捐{
试一试{
HttpClient HttpClient=新的DefaultHttpClient();
HttpPost HttpPost=新的HttpPost(“http://justedhak.comlu.com/images/upload_image.php");
setEntity(新的UrlEncodedFormEntity(nameValuePairs));
HttpResponse response=httpclient.execute(httppost);
最终字符串\u字符串\u响应=convertResponseToString(响应);
runOnUiThread(新的Runnable(){
@凌驾
import com.squareup.okhttp.OkHttpClient;
import com.squareup.okhttp.Request;
import com.squareup.okhttp.Response;
import java.io.IOException;

public class MainActivity {
    OkHttpClient client = new OkHttpClient();

    String run(String url) throws IOException {
        Request request = new Request.Builder()
                .url(url)
                .build();

        Response response = client.newCall(request).execute();
        return response.body().string();
    }

    public static void main(String[] args) throws IOException {
        MainActivity example = new MainActivity();
        String response = example.run("https://raw.github.com/square/okhttp/master/README.md");
        System.out.println(response);
    }
}
package com.example.justedhak;

import java.io.ByteArrayOutputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Calendar;

import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Spinner;
import android.widget.Toast;

public class AddImage extends Activity {
    InputStream inputStream;
    String categorie;
    String caption;
//  private Bitmap bmp;
    ImageView imageview;
        @Override
    public void onCreate(Bundle icicle) {
            super.onCreate(icicle);
            setContentView(R.layout.main);

            //get values
            EditText captionetxt = (EditText) findViewById(R.id.caption);
            caption = captionetxt.getText().toString();
            //spinner
            Spinner dropdown = (Spinner)findViewById(R.id.spinner1);
            String[] items = new String[]{"Lebanese jokes", "Student Jokes", "Quotes"};
            ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, items);
            dropdown.setAdapter(adapter);

            categorie = dropdown.getSelectedItem().toString();
            imageview = (ImageView) findViewById(R.id.imageView);


            Intent intent = getIntent();
            String selectedImage= intent.getStringExtra("imagePath");
            Uri fileUri = Uri.parse(selectedImage);

            InputStream imageStream = null;
            try {
                imageStream = getContentResolver().openInputStream(fileUri);
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            }
            Bitmap bmp = BitmapFactory.decodeStream(imageStream);

            ByteArrayOutputStream stream = new ByteArrayOutputStream();
            bmp.compress(Bitmap.CompressFormat.JPEG, 30, stream);


            byte[] byteArray = stream.toByteArray();
            Bitmap bitmap = BitmapFactory.decodeByteArray(byteArray, 0, byteArray.length);
            imageview.setImageBitmap(bitmap);
                }
        public void onclick(View view)
        {
            Toast.makeText(AddImage.this, "Uploading Image", Toast.LENGTH_LONG).show();                         
            upload();

              Intent i = new Intent(this,
                        MainActivity.class);
              startActivity(i);

        }
        public void upload()
        {
              Calendar thisCal = Calendar.getInstance();
              thisCal.getTimeInMillis();

              //  android.util.Log.i("Time Class ", " Time value in millisecinds "+ thisCal);

           // Bitmap bitmap = BitmapFactory.decodeResource(getResources(),R.drawable.ic_launcher);  
         //   ByteArrayOutputStream stream = new ByteArrayOutputStream();
           // bmp.compress(Bitmap.CompressFormat.PNG, 90, stream); //compress to which format you want.
            // up in oncreate
              Intent intent = getIntent();
                String selectedImage= intent.getStringExtra("imagePath");
                Uri fileUri = Uri.parse(selectedImage);
            System.out.println(fileUri);

            InputStream imageStream = null;
            try {
                imageStream = getContentResolver().openInputStream(fileUri);
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            }

            Bitmap bmp = BitmapFactory.decodeStream(imageStream);

            ByteArrayOutputStream stream = new ByteArrayOutputStream();
            bmp.compress(Bitmap.CompressFormat.JPEG, 30, stream);


            byte[] byteArray = stream.toByteArray();
            Bitmap bitmap = BitmapFactory.decodeByteArray(byteArray, 0, byteArray.length);
            imageview.setImageBitmap(bitmap); 
            int width = bitmap.getWidth();
            int height = bitmap.getHeight();
            System.out.println(width);
            System.out.println(height);


            getResizedBitmap( bitmap, 200);
            try {
                stream.close();
                stream = null;
            } catch (IOException e) {

                e.printStackTrace();
            }

            String image_str = Base64.encodeBytes(byteArray);
            final ArrayList<NameValuePair> nameValuePairs = new  ArrayList<NameValuePair>();
            nameValuePairs.add(new BasicNameValuePair("image",image_str));
            nameValuePairs.add(new BasicNameValuePair("caption",caption));
            nameValuePairs.add(new BasicNameValuePair("name","je"));
            nameValuePairs.add(new BasicNameValuePair("categorie",categorie));
             Thread t = new Thread(new Runnable() {

            @Override
            public void run() {
                  try{

                         HttpClient httpclient = new DefaultHttpClient();
                         HttpPost httppost = new HttpPost("http://justedhak.comlu.com/images/upload_image.php");
                         httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
                         HttpResponse response = httpclient.execute(httppost);
                         final String the_string_response = convertResponseToString(response);
                         runOnUiThread(new Runnable() {

                                @Override
                                public void run() {
                                    Toast.makeText(AddImage.this, "Response " + the_string_response, Toast.LENGTH_LONG).show();                         
                                }
                            });

                     }catch(final Exception e){
                          runOnUiThread(new Runnable() {

                            @Override
                            public void run() {
                                Toast.makeText(AddImage.this, "ERROR " + e.getMessage(), Toast.LENGTH_LONG).show();                             
                            }
                        });
                           System.out.println("Error in http connection "+e.toString());
                     }  
            }
        });
         t.start();
        }

        public String convertResponseToString(HttpResponse response) throws IllegalStateException, IOException{

             String res = "";
             StringBuffer buffer = new StringBuffer();
             inputStream = response.getEntity().getContent();
             final int contentLength = (int) response.getEntity().getContentLength(); //getting content length…..
              runOnUiThread(new Runnable() {

            @Override
            public void run() {
                Toast.makeText(AddImage.this, "contentLength : " + contentLength, Toast.LENGTH_LONG).show();                        
            }
        });

             if (contentLength < 0){
             }
             else{
                    byte[] data = new byte[512];
                    int len = 0;
                    try
                    {
                        while (-1 != (len = inputStream.read(data)) )
                        {
                            buffer.append(new String(data, 0, len)); //converting to string and appending  to stringbuffer…..
                        }
                    }
                    catch (IOException e)
                    {
                        e.printStackTrace();
                    }
                    try
                    {
                        inputStream.close(); // closing the stream…..
                    }
                    catch (IOException e)
                    {
                        e.printStackTrace();
                    }
                    res = buffer.toString();     // converting stringbuffer to string…..

                    runOnUiThread(new Runnable() {

                    @Override
                    public void run() {
                       Toast.makeText(AddImage.this, "Result : res", Toast.LENGTH_LONG).show();
                    }
                });
                    //System.out.println("Response => " +  EntityUtils.toString(response.getEntity()));
             }
             return res;
        }

        public Bitmap getResizedBitmap(Bitmap image, int maxSize) {
            int width = image.getWidth();
            int height = image.getHeight();

            float bitmapRatio = (float)width / (float) height;
            if (bitmapRatio > 0) {
                width = maxSize;
                height = (int) (width / bitmapRatio);
            } else {
                height = maxSize;
                width = (int) (height * bitmapRatio);
            }
            return Bitmap.createScaledBitmap(image, width, height, true);
    }



}
import android.util.Log;

import com.squareup.okhttp.OkHttpClient;
import com.squareup.okhttp.Request;
import com.squareup.okhttp.Response;

import java.io.IOException;

public class MainActivity extends Activity {
    private static final String TAG = "MainActivity";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
         super.onCreate(savedInstanceState);
         setContentView(R.layout.your_layout);

         try {
             String response = getResponse("https://raw.github.com/square/okhttp/master/README.md");
             Log.d(TAG, response);
         } catch (IOException ioe) {
             Log.e(TAG, ioe.getMessage());
         }
    }

    private String getResponse(String url) throws IOException {
        OkHttpClient client = new OkHttpClient();
        Request request = new Request.Builder()
                                     .url(url)
                                     .build();

        Response response = client.newCall(request).execute();
        return response.body().string();
    }
}
OkHttpClient client = new OkHttpClient();
Request request = new Request.Builder()
       .url(url)
       .build();

Response response = client.newCall(request).execute();
return response.body().string();