android将数据从活动传递到类。发布到PHP

时间:2016-07-10 05:48:59

标签: php android android-intent android-activity

我一直试图让这个工作好几天。

当我上传音频文件时,如何获取用户名以发布到PHP文件?

在我的Loggedin活动中,用户在我的JoinView活动传递的文本字段中显示了uername。作品。我正在录制一段时间,当用户点击一个按钮时,一旦录制完成,它就会将文件发布到服务器。在我开始之前也有效。我在将Uploads.php文件的用户名获取时遇到问题。 Upload方法在我的Upload.java类中。从Loggedin活动调用。所以,我不认为我的用户名会被发布到php文件中。不确定。

这是我的LoggedIn活动。



import android.os.CountDownTimer;

import java.util.HashMap;
import java.util.Map;

import android.app.ProgressDialog;
import android.net.Uri;
import android.os.AsyncTask;
import android.media.MediaRecorder;
import android.os.Environment;
import android.view.View;

import java.io.File;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.media.MediaPlayer;
import android.widget.TextView;

import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import com.google.android.gms.appindexing.Action;
import com.google.android.gms.appindexing.AppIndex;
import com.google.android.gms.common.api.GoogleApiClient;


//import android.media.MediaRecorder;
//import android.net.Uri;
//import android.os.CountDownTimer;
//import android.os.Environment;


public class LoggedIn extends AppCompatActivity {


  //  private static String myVarible = null;

  //  private void myMethod(){
  //      myVarible = (getIntent().getExtras().getString("user"));
  //  }

  //  public static String getVariable(){
  //      return myVarible;

//    }

    public static final String KEY_USERNAMEPUSH = "usernamepush";
    public static final String POSTUSERNAME= "http://myuploadlocation/file/uploads.php";
    private TextView textviewuser;

    long starttimer = 0;
    private MediaRecorder recorder;
    private String OUTPUT_FILE;
    private MediaPlayer mediaPlayer;
    /**
     * ATTENTION: This was auto-generated to implement the App Indexing API.
     * See https://g.co/AppIndexing/AndroidStudio for more information.
     */
    private GoogleApiClient client;
    //private static final int SELECT_VIDEO = 3;
   // private String selectedPath;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_logged_in);
        // OUTPUT_FILE=Environment.get
        TextView nameView=(TextView) findViewById(R.id.textviewuser);
        nameView.setText(getIntent().getExtras().getString("user"));
       // File extStore = Environment.getExternalStorageDirectory();
        OUTPUT_FILE = Environment.getExternalStorageDirectory() +"/1.3gpp";
        // 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();
        TextView timeTextView = (TextView) findViewById(R.id.mTextField);
        timeTextView.setText("8");
        textviewuser = (TextView) findViewById(R.id.textviewuser);


    }


    public void buttonTapped(View v) {
        switch (v.getId()) {
            case R.id.bRecord:
                try {
                    beginRecording();
                } catch (Exception e) {
                    e.printStackTrace();
                }
                break;
            //case R.id.bStop:
             //   try {
              //      stopRecording();
              //  } catch (Exception e) {
              //      e.printStackTrace();
              //  }
               // break;
            case R.id.bPlay:
                try {
                    playRecording();
                } catch (Exception e) {
                    e.printStackTrace();
                }
                break;
        }
    }

    private void beginRecording() throws Exception {
        ditchMediaRecorder();
        ///////////////////////////////////////////////////////////////////////////////////

        //post uername to upload.php file to get the user id in the php file with a query.
        //final String usernamepush = (getIntent().getExtras().getString("user"));

       // usernameis = (EditText) findViewById(R.id.textviewuser);


        final TextView usernamepush = (TextView) findViewById(R.id.textviewuser);

        StringRequest stringRequestlogin = new StringRequest(Request.Method.POST, POSTUSERNAME,
                new Response.Listener<String>(){
       ject jsonResponse = new JSONObject(response);
                      
                    }

                },
                new Response.ErrorListener(){
                    @Override
                    public void onErrorResponse(VolleyError error) {
                        //Toast.makeText(Login.this,error.toString(),Toast.LENGTH_LONG).show();
                    }

                }){

            @Override
            protected Map<String, String> getParams(){
                Map<String, String> params = new HashMap<>();
                params.put(KEY_USERNAMEPUSH, String.valueOf(usernamepush));

                return params;
            }
        };
        RequestQueue requestQueuel = Volley.newRequestQueue(this);
        requestQueuel.add(stringRequestlogin);
 
        //////////////////////////////////////////////////////////////////////////////////





        File outFile = new File(OUTPUT_FILE);

        //if the file is already there. Delete it.
        if (outFile.exists())
            outFile.delete();

        recorder = new MediaRecorder();
        recorder.setAudioSource(MediaRecorder.AudioSource.MIC);
        recorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);
        recorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);
        recorder.setOutputFile(OUTPUT_FILE);
        recorder.prepare();
        recorder.start();
        new CountDownTimer(8000, 1000) {

            public void onTick(long millisUntilFinished) {
               TextView timeTextView = (TextView) findViewById(R.id.mTextField);
               timeTextView.setText(String.valueOf(millisUntilFinished/1000));


            }

            public void onFinish() {
            recorder.stop();
                recorder.release();
                TextView timeTextView = (TextView) findViewById(R.id.mTextField);

                timeTextView.setText("8");
                uploadVideo();
            }

            private void uploadVideo() {class UploadVideo extends AsyncTask<Void, Void, String> {

                ProgressDialog uploading;

                @Override
                protected void onPreExecute() {
                    super.onPreExecute();
                    uploading = ProgressDialog.show(LoggedIn.this, "Uploading Your Recording", "Please wait...", false, false);
                }

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

                @Override
                protected String doInBackground(Void... params) {
                    Upload u = new Upload();
                    String msg = u.uploadVideo(OUTPUT_FILE);
                    return msg;
                }

            }
                UploadVideo uv = new UploadVideo();
                uv.execute();
            }
        }.start();

    }

    private void ditchMediaRecorder() {
        if (recorder != null)
            recorder.release();

    }

    private void stopRecording() {

        if (recorder != null)
            recorder.stop();


    }

    private void playRecording() throws Exception {
        ditchMediaPlay();
        mediaPlayer = new MediaPlayer();
        mediaPlayer.prepare();
        mediaPlayer.start();


    }

    private void ditchMediaPlay() {
        if (mediaPlayer != null) {
            try {
                mediaPlayer.release();

            } catch (Exception e) {
                e.printStackTrace();

            }

        }

    }


    @Override
    public void onStart() {
        super.onStart();
wAction = Action.newAction(
                Action.TYPE_VIEW, // TODO: choose an action type.
                "LoggedIn Page", // TODO: Define a title for the content shown.
                // TODO: If you have web page content that matches this app activity's content,
                // make sure this auto-generated web page URL is correct.
                // Otherwise, set the URL to null.
                Uri.parse("http://host/path"),
                // TODO: Make sure this auto-generated app URL is correct.
                Uri.parse("android-app://com.example.myapp.myapp/http/host/path")
        );
        AppIndex.AppIndexApi.start(client, viewAction);
    }

    @Override
    public void onStop() {
        super.onStop();

        Action viewAction = Action.newAction(
                Action.TYPE_VIEW, // TODO: choose an action type.
                "LoggedIn Page", // TODO: Define a title for the content shown.
                // TODO: If you have web page content that matches this app activity's content,
                // make sure this auto-generated web page URL is correct.
                // Otherwise, set the URL to null.
                Uri.parse("http://host/path"),
                // TODO: Make sure this auto-generated app URL is correct.
                Uri.parse("android-app://com.example.myapp.myapp/http/host/path")
        );
        AppIndex.AppIndexApi.end(client, viewAction);
        client.disconnect();
    }


}
&#13;
&#13;
&#13;

这是我的Upload.php文件

&#13;
&#13;
<?

include 'connect.php';

$username = $_POST['usernamepush'];

$userid = "SELECT id FROM `users` WHERE username ='".$username."'";

$resultid = mysql_query($userid) or die('Error connecting to database');
$user_id = mysql_result($resultid, 0, "id");
////////////////////////////////////////////////////////////////////////////////////////////
	if($_SERVER['REQUEST_METHOD']=='POST'){
		$file_name = $_FILES['myFile']['name'];
		$file_size = $_FILES['myFile']['size'];
		$file_type = $_FILES['myFile']['type'];
		$temp_name = $_FILES['myFile']['tmp_name'];
				
		$location = "users/".$user_id."/";
			
		move_uploaded_file($temp_name, $location.$file_name);
		echo "http://www.mywebsite.com/myfile/users/".$file_name;
	}else{
		echo "Error";
	}
?>
&#13;
&#13;
&#13;

这是我的Upload.java类

&#13;
&#13;
import android.util.Log;

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
//import android.widget.ImageView;

/**
 * Created by mikedhane on 7/3/16.
 */




public class Upload {





    public static final String UPLOAD_URL= "http://mywesite.com/files/uploads.php";
    private int serverResponseCode;

    public String uploadVideo(String file) {

        String fileName = file;
        HttpURLConnection conn = null;
        DataOutputStream dos = null;
        String lineEnd = "\r\n";
        String twoHyphens = "--";
        String boundary = "*****";
        int bytesRead, bytesAvailable, bufferSize;
        byte[] buffer;
        int maxBufferSize = 1 * 1024 * 1024;

        File sourceFile = new File(file);
        if (!sourceFile.isFile()) {
            Log.e("Huzza", "Source File Does not exist");
            return null;
        }

        try {
            FileInputStream fileInputStream = new FileInputStream(sourceFile);
            URL url = new URL(UPLOAD_URL);
            conn = (HttpURLConnection) url.openConnection();
            conn.setDoInput(true);
            conn.setDoOutput(true);
            conn.setUseCaches(false);
            conn.setRequestMethod("POST");
            conn.setRequestProperty("Connection", "Keep-Alive");
            conn.setRequestProperty("ENCTYPE", "multipart/form-data");
            conn.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + boundary);
            conn.setRequestProperty("myFile", fileName);
            dos = new DataOutputStream(conn.getOutputStream());

            dos.writeBytes(twoHyphens + boundary + lineEnd);
            dos.writeBytes("Content-Disposition: form-data; name=\"myFile\";filename=\"" + fileName + "\"" + lineEnd);
            dos.writeBytes(lineEnd);

            bytesAvailable = fileInputStream.available();
            Log.i("Huzza", "Initial .available : " + bytesAvailable);

            bufferSize = Math.min(bytesAvailable, maxBufferSize);
            buffer = new byte[bufferSize];

            bytesRead = fileInputStream.read(buffer, 0, bufferSize);

            while (bytesRead > 0) {
                dos.write(buffer, 0, bufferSize);
                bytesAvailable = fileInputStream.available();
                bufferSize = Math.min(bytesAvailable, maxBufferSize);
                bytesRead = fileInputStream.read(buffer, 0, bufferSize);
            }

            dos.writeBytes(lineEnd);
            dos.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);

            serverResponseCode = conn.getResponseCode();

            fileInputStream.close();
            dos.flush();
            dos.close();
        } catch (MalformedURLException ex) {
            ex.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }

        if (serverResponseCode == 200) {
            StringBuilder sb = new StringBuilder();
            try {
                BufferedReader rd = new BufferedReader(new InputStreamReader(conn
                        .getInputStream()));
                String line;
                while ((line = rd.readLine()) != null) {
                    sb.append(line);
                }
                rd.close();
            } catch (IOException ioex) {
            }
            return sb.toString();
        }else {
            return "Could not upload";
        }
    }


}
&#13;
&#13;
&#13;

我不认为我得到了usernamepush到php文件。就像我说的那样,它被传递给LoggedIn Activity并显示给用户。

请帮助。

0 个答案:

没有答案