Android studio: диалоговые окна с кнопкой Да и Нет

За построение диалоговых окон в Android отвечает класс AlertDialog. С помощью него довольно легко построить конструкцию, чтото типа:

 AlertDialog.Builder builder = new AlertDialog.Builder(cntcur);
                builder.setTitle("Вопрос!");
                builder.setMessage("Будем удалять фото?");
                builder.setCancelable(true);
                builder.setPositiveButton("ДА", new DialogInterface.OnClickListener() { // Кнопка Да
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss(); // Отпускает диалоговое окно
                        map=arrayList.get(position);
                        Log.i("Info","--выбрали удалить");
                    }
                });
                builder.setNegativeButton("Конечно нет", new DialogInterface.OnClickListener() { // Кнопка Нет
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss(); // Отпускает диалоговое окно
                    }
                });
                AlertDialog dialog = builder.create();
                dialog.show();

Android Studio: ListView c фотографией и текстом

Задача: разместить в виджете ListView картинку из файла + текст. Результат должен выглядеть как то так:

Решение: будем писать свой «адаптер», на входе которого будет массив из id и photo_name (имя файла картинки)

Экран list_photos.xml:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 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">

    <ImageView
        android:id="@+id/imgv"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        tools:srcCompat="@tools:sample/avatars" />

    <TextView
        android:id="@+id/photo_id"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        android:text="photo_id" />

    <TextView
        android:id="@+id/photo_name"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        android:text="photo_name" />
</LinearLayout>

Код адаптера:

        ListView listView = findViewById(R.id.ListPhotos);
        // используем адаптер данных
        adapter=new PhotosAdapter(this,R.layout.list_photos, arrayList);
        listView.setAdapter(adapter);


    }
    // Пишем свой класс-адаптер
    private class PhotosAdapter extends ArrayAdapter<String> {
        PhotosAdapter(Context context, int textViewResourceId, ArrayList objects) {
            super(context, textViewResourceId, objects);
        }
        @NonNull
        @Override
        public View getView(int position, @Nullable View convertView, @NonNull ViewGroup parent) {
            LayoutInflater inflater = getLayoutInflater();
            View row = inflater.inflate(R.layout.list_photos, parent, false);
            map=arrayList.get(position);
            TextView pid = (TextView) row.findViewById(R.id.photo_id);
            TextView pname = (TextView) row.findViewById(R.id.photo_name);
            File imgFile = new  File(map.get("photo_name"));
            pid.setText(map.get("photo_id"));
            Bitmap myBitmap = BitmapFactory.decodeFile(imgFile.getAbsolutePath());
            ImageView iconImageView = (ImageView) row.findViewById(R.id.imgv);
            iconImageView.setImageBitmap(myBitmap);
            return row;
        }
    }

Android: сделать фото и сохранить в папке приложения

Задача: по кнопке сделать в приложении фото, и сохранить его с уникальным именем в папку приложения.

Решение:

1) Поправим файл AndroidManifest.xml:

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android" package="eee.photossinhro">
    <uses-feature android:name="android.hardware.camera" android:required="true" />
    <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
    <application
	...
        <provider
            android:name="android.support.v4.content.FileProvider"
            android:authorities="eee.fileprovider"
            android:grantUriPermissions="true"
            android:exported="false">
            <meta-data
                android:name="android.support.FILE_PROVIDER_PATHS"
                android:resource="@xml/filepaths" />
        </provider>
	...
    </application>
</manifest>

2) Добавим файл /xml/filepath.xml в папке res:

<?xml version="1.0" encoding="utf-8"?>
<paths xmlns:android="http://schemas.android.com/apk/res/android">
    <external-path name="photossinhro"
        path="Android/data/eee.photossinhro/files/Pictures" />
</paths>

3) Код приложения примерно следующий:

package eee.photossinhro;

import android.content.ActivityNotFoundException;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.v4.content.FileProvider;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.CardView;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.Toast;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;

import static android.media.tv.TvTrackInfo.TYPE_VIDEO;

public class PhotosActivity extends AppCompatActivity {
    String id; //идентификатор аккаунта
    private Context cntcur;

    static final int REQUEST_PICTURE_CAPTURE = 1;
    private ImageView image;
    private String pictureFilePath;

    private File getPictureFile() throws IOException {
        String timeStamp = new SimpleDateFormat("yyyyMMddHHmmss").format(new Date());
        String pictureFile = "photossinhro" + timeStamp;
        File storageDir = getExternalFilesDir(Environment.DIRECTORY_PICTURES);
        File image = File.createTempFile(pictureFile,  ".jpg", storageDir);
        pictureFilePath = image.getAbsolutePath();
        Log.i("Info", "--путь:"+pictureFilePath);
        return image;
    }
    private void sendTakePictureIntent() {
        Intent cameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        cameraIntent.putExtra( MediaStore.EXTRA_FINISH_ON_COMPLETION, true);
        if (cameraIntent.resolveActivity(getPackageManager()) != null) {
            startActivityForResult(cameraIntent, REQUEST_PICTURE_CAPTURE);
            File pictureFile = null;
            try {
                pictureFile = getPictureFile();
            } catch (IOException ex) {
                Toast.makeText(this, "Photo file can't be created, please try again", Toast.LENGTH_SHORT).show();
                return;
            }
            if (pictureFile != null) {
                Uri photoURI = FileProvider.getUriForFile(this, "eee.photossinhro.fileprovider", pictureFile);
                cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, photoURI);
                startActivityForResult(cameraIntent, REQUEST_PICTURE_CAPTURE);
            }
        }
    }
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_photos);

        id = getIntent().getExtras().getString("id");

        Log.i("Info","--мы в новой активности! ID="+id);
        cntcur=this;
        // нажата кнопка "сделать фото"
        Button button = (Button) findViewById(R.id.CreatePhotos);
        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Log.i("Info", "--нажата кнопка сделать фото");
                if(getPackageManager().hasSystemFeature(PackageManager.FEATURE_CAMERA)){
                    sendTakePictureIntent();
                }
            }
        });

    }
}

Получение страницы по http протоколу на Android

Задача: получить «сырой» json  по протоколу http в приложении под андроид.

Решение:

1)  Разрешим доступ в интернет в AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="ru.erver.noc.nocmessages">
    <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
    <uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
    <application
        android:resource="@xml/netsec"
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:supportsRtl="true"
        android:theme="@style/Theme.AppCompat.NoActionBar" >
        <activity android:name=".Form1">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

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

</manifest>

2) Код:

package ru.yarteleservice.noc.nocmessages;

import android.content.SharedPreferences;
import android.os.AsyncTask;
import android.preference.PreferenceManager;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.EditText;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;

public class Form1 extends AppCompatActivity {
    EditText logv;
    jsonnoc jsn;

    public void AddToLog(String txt) {
        logv = (EditText) findViewById(R.id.editText3);
        if (txt == "clear") {
            logv.setText("");
        } else {
            logv.append(txt);
            logv.append("\n");
        }
        ;
    }

    ;

    public void ClickEnterNocButton(View view) {

        Log.d("неашипка", "--click!");
        AddToLog("clear");

        EditText elogin = (EditText) findViewById(R.id.editText);
        EditText epass = (EditText) findViewById(R.id.editText2);

        AddToLog("-пробуем залогиниться");
        // jsonnoc jsn=new jsonnoc();
        //jsn.GetJsonMet("{'userlogin':'login'}");
        new GetMyDataFromUrl().execute("!!!!!!!!!");

        AddToLog("-сохраняем настройки");

        SharedPreferences mSettings = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
        SharedPreferences.Editor mEdit = mSettings.edit();
        mEdit.putString("userlogin", elogin.getText().toString());
        mEdit.commit();
        mEdit.apply();
        mEdit.putString("userpass", epass.getText().toString());
        mEdit.commit();
        mEdit.apply();

    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_form1);
        AddToLog("-читаем настройки");

        EditText elogin = (EditText) findViewById(R.id.editText);
        EditText epass = (EditText) findViewById(R.id.editText2);

        SharedPreferences mSettings = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());

        elogin.setText(mSettings.getString("userlogin", ""));
        epass.setText(mSettings.getString("userpass", ""));

        AddToLog(elogin.getText().toString());
        AddToLog(epass.getText().toString());

    }

    class GetMyDataFromUrl extends AsyncTask<String, Integer, String>{

        @Override
        protected String doInBackground(String... arg) {
            String res;
            BufferedReader reader = null;
            String resultJson = "";

            res=null;
            HttpURLConnection urlConnection = null;
            Log.d("неашипка", "--пробую почитать json");
            try {
                URL url = new URL("http://noc.dfvdfv.ru/getjsonmess.php");
                urlConnection = (HttpURLConnection) url.openConnection();
                urlConnection.setRequestMethod("GET");
                urlConnection.connect();

                InputStream inputStream = urlConnection.getInputStream();
                StringBuffer buffer = new StringBuffer();

                reader = new BufferedReader(new InputStreamReader(inputStream));

                String line;
                while ((line = reader.readLine()) != null) {
                    buffer.append(line);
                }
                resultJson = buffer.toString();
                Log.d("неашипка", resultJson);
            }
            catch (Exception e) {
                e.printStackTrace();
                Log.d("ашипка", "--не смогли прочитать JSON");
            }
            return res;
        }

        @Override
        protected void onPostExecute(String s) {
            super.onPostExecute(s);
        }
    }
}

Результат:




Установка JDK7 на debian wheezy

echo "deb http://ppa.launchpad.net/webupd8team/java/ubuntu precise main" | tee -a /etc/apt/sources.list
echo "deb-src http://ppa.launchpad.net/webupd8team/java/ubuntu precise main" | tee -a /etc/apt/sources.list
apt-key adv --keyserver hkp://keyserver.ubuntu.com:80 --recv-keys EEA14886
apt-get update
apt-get install oracle-java7-installer