第一次使用okhttp崩溃

时间:2015-09-22 18:34:54

标签: android okhttp

我正在尝试使用github simple 示例的okHttp 但是我有这个错误..检查下面的logcat

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>

主要活动

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);
    }



}

2 个答案:

答案 0 :(得分:1)

link中的GetExample不是活动。

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();
    }
}

请确保在顶部和其他所需导入中包含正确的包名称。这是未经测试的代码。

答案 1 :(得分:1)

您需要在AsyncTask中调用以下行:

OkHttpClient client = new OkHttpClient();
Request request = new Request.Builder()
       .url(url)
       .build();

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

它对我有用