0

Here is my code. I am getting error in this , please help me complete it. I am trying to post a http request to my server with some data in my android app.

        package com.example.firstapp;

import android.app.Activity;
import android.graphics.drawable.AnimationDrawable;
import android.hardware.Sensor;
import android.hardware.SensorManager;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnCompletionListener;
import android.os.Bundle;
import android.view.View;
import android.view.animation.AlphaAnimation;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;

import com.example.firstapp.ShakeDetector.OnShakeListener;

public class MainActivity extends Activity {

    private CrystalBall mCrystalBall = new CrystalBall();
    private ApiCall mApiCall = new ApiCall();
    private TextView mAnswerLabel;
    private Button mGetAnswerButton;
    private ImageView mCrystalBallImage;
    private SensorManager mSensorManager;
    private Sensor mAccelerometer;
    private ShakeDetector mShakeDetector;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        //Assign the Views from the layout file
        mAnswerLabel = (TextView) findViewById(R.id.textView1);
        mGetAnswerButton = (Button) findViewById(R.id.button1);
        mCrystalBallImage = (ImageView) findViewById(R.id.imageView1);

        mGetAnswerButton.setOnClickListener(new View.OnClickListener() {

            public void onClick(View arg0) {
                handleNewAnswer();
                mApiCall.postData();
            }
        });

        mSensorManager = (SensorManager) getSystemService(SENSOR_SERVICE);
        mAccelerometer = mSensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
        mShakeDetector = new ShakeDetector(new OnShakeListener() {

            @Override
            public void onShake() {
                handleNewAnswer();
            }
        });
        //Toast.makeText(this, "Yes this is toast", Toast.LENGTH_LONG).show();
        //Log.d("Main Activity", "from oncreate() function");
    }

    @Override
    public void onResume() {
        super.onResume();
        mSensorManager.registerListener(mShakeDetector, mAccelerometer, 
                SensorManager.SENSOR_DELAY_UI);
    }

    @Override
    public void onPause() {
        super.onPause();
        mSensorManager.unregisterListener(mShakeDetector);
    }

    private void animateCrystalBAll() {
        mCrystalBallImage.setImageResource(R.drawable.ball_animation);
        AnimationDrawable ballAnimtion = (AnimationDrawable) mCrystalBallImage.getDrawable();
        if(ballAnimtion.isRunning()) {
            ballAnimtion.stop();
        }
        ballAnimtion.start();
    }

    private void animateAnswer() {
        AlphaAnimation fadeInAnimation = new AlphaAnimation(0, 1);
        fadeInAnimation.setDuration(1500);
        fadeInAnimation.setFillAfter(true);
        mAnswerLabel.setAnimation(fadeInAnimation);
    }

    private void playSound() {
        MediaPlayer player = MediaPlayer.create(this, R.raw.crystal_ball);
        player.start();
        player.setOnCompletionListener(new OnCompletionListener() {

            @Override
            public void onCompletion(MediaPlayer mp) {
                mp.release();
            }
        });
    }



}

Here is ApiCall.java. In this file I am using http post request

package com.example.firstapp;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
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.os.AsyncTask;

public class ApiCall extends AsyncTask {
    public void postData() {
        HttpClient httpclient = new DefaultHttpClient();    
          HttpPost httppost = new HttpPost("http://dailydeal.in/android/Api.php");      
                try {        

                     List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();        
                     nameValuePairs.add(new BasicNameValuePair("gmail","mail@gmail.com"));

                     httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs)); 
                    HttpResponse response = httpclient.execute(httppost);             
                 } 
                catch (ClientProtocolException e) 
                {       
                     e.printStackTrace(); 
                 } 
                catch (IOException e) 
                {         
                     e.printStackTrace();
                  }
    }

    @Override
    protected Object doInBackground(Object... arg0) {
        // TODO Auto-generated method stub
        return null;
    } 
}
Suneel Kumar
  • 5,621
  • 3
  • 31
  • 44

2 Answers2

1
  • Please make sure that you have requested INTERNET permission on manifest

  • postData() function must be called on separate thread because you can't run request network on main thread. You can user Asynctask or service

    private class PostDataAsynTask extends AsyncTask {

    @Override
    protected void onPreExecute() {
        // TODO Auto-generated method stub
        super.onPreExecute();
    
    }
    
    
    @Override
    protected ApiModel doInBackground(String... params) {
    
        // Call your post data funciton here
        return null;
    }
    
    @Override
    protected void onPostExecute(ApiModel result) {
        // TODO Auto-generated method stub
        super.onPostExecute(result);
    
        // Do your stuff after post data here
    }
    

    }

Then on you MainActivity

new PostDataAsynTask().excute("");
  • I have giver permission for internet. I have postData() in a class name ApiCall other than MainActivity. – Suneel Kumar Apr 28 '14 at 09:58
  • Can you post logcat ? – user3579893 Apr 28 '14 at 10:03
  • 04-28 06:13:57.835: E/AndroidRuntime(2949): Process: com.example.firstapp, PID: 2949 04-28 06:13:57.835: E/AndroidRuntime(2949): android.os.NetworkOnMainThreadException 04-28 06:13:57.835: E/AndroidRuntime(2949): at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1145) – Suneel Kumar Apr 28 '14 at 10:17
  • ==> postData() function must be called on separate thread because you can't run request network on main thread. You can user Asynctask or service I mean you should create new separate thread to call postData() functions. Please see my new answer – user3579893 Apr 28 '14 at 10:37
  • I have postData in new class name ApiCall.java Please see my updated question. where is your new answer – Suneel Kumar Apr 28 '14 at 10:40
  • Please put code on postData in onDoInbackground() functions. And call : APICall.excute(); to excute your post data code. I updated my answer, not new answer, sorry – user3579893 Apr 28 '14 at 10:44
  • should I create a new function called onDoInbackground() – Suneel Kumar Apr 28 '14 at 10:47
  • No, just override it. Please see this tutorial (6.5 Asynctask) http://www.vogella.com/tutorials/AndroidBackgroundProcessing/article.html And google doc for more detail about Asynctask http://developer.android.com/reference/android/os/AsyncTask.html – user3579893 Apr 28 '14 at 10:49
0

try this

  HttpClient httpclient = new DefaultHttpClient();    
  HttpPost httppost = new HttpPost(YOUR URL);      
        try {        

             List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();        
             nameValuePairs.add(new BasicNameValuePair("gmail","mail@gmail.com"));

             httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs)); 
            HttpResponse response = httpclient.execute(httppost);             
         } 
        catch (ClientProtocolException e) 
        {       
             e.printStackTrace(); 
         } 
        catch (IOException e) 
        {         
             e.printStackTrace();
          }

make sure that your database contains field "gmail"

php

   <?php

    mysql_connect("localhost","username","password");

    mysql_select_db("db_name"); 


    $a1= (isset($_POST['gmail'])) ? $_POST['gmail'] : '';

    $ins="insert into Table_name(gmail)values('$a1')";

    mysql_query($ins);
     mysql_close();
   ?>
Maxwell
  • 552
  • 2
  • 5
  • 20
  • 04-28 06:13:57.835: E/AndroidRuntime(2949): FATAL EXCEPTION: main 04-28 06:13:57.835: E/AndroidRuntime(2949): Process: com.example.firstapp, PID: 2949 04-28 06:13:57.835: E/AndroidRuntime(2949): android.os.NetworkOnMainThreadException 04-28 06:13:57.835: E/AndroidRuntime(2949): at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1145) 04-28 06:13:57.835: E/AndroidRuntime(2949): at java.net.InetAddress.lookupHostByName(InetAddress.java:385) – Suneel Kumar Apr 28 '14 at 10:19
  • 04-28 06:13:57.835: E/AndroidRuntime(2949): at java.net.InetAddress.getAllByNameImpl(InetAddress.java:236) 04-: E/AndroidRuntime(2949): at java.net.InetAddress.getAllByName(InetAddress.java:214) 04-2 E/AndroidRuntime(2949): at org.apache.http.impl.conn.DefaultClientConnectionOperator.openConnection(DefaultClientConnectionOperator.java:137) 04-28 06:13:57.835: E/AndroidRuntime(2949): at org.apache.http.impl.conn.AbstractPoolEntry.open(AbstractPoolEntry.java:164) : E/AndroidRuntime(2949): at org.apache.http.impl.conn.AbstractPooledConnAdapter.open(AbstractPooledConnAdapter.java:119) – Suneel Kumar Apr 28 '14 at 10:19
  • 04-28 06:13:57.835: E/AndroidRuntime(2949): at org.apache.http.impl.client.DefaultRequestDirector.execute(DefaultRequestDirector.java:360) 04-28 06:13:57.835: E/AndroidRuntime(2949): at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:555) – Suneel Kumar Apr 28 '14 at 10:20
  • 04-28 06:13:57.835: E/AndroidRuntime(2949): at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:487) 04-28 06:13:57.835: E/AndroidRuntime(2949): at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:465) 04-28 06:13:57.835: E/AndroidRuntime(2949): at com.example.firstapp.ApiCall.postData(ApiCall.java:30) – Suneel Kumar Apr 28 '14 at 10:21
  • add these lines in your post code StrictMode.ThreadPolicy policy2 = new StrictMode.ThreadPolicy.Builder().permitAll().build(); StrictMode.setThreadPolicy(policy2); – Maxwell Apr 28 '14 at 10:28
  • 04-28 06:13:57.835: E/AndroidRuntime(2949): at com.example.firstapp.MainActivity$1.onClick(MainActivity.java:58) 04-28 06:13:57.835: E/AndroidRuntime(2949): at android.view.View.performClick(View.java:4438) 04-28 06:13:57.835: E/AndroidRuntime(2949): at android.view.View$PerformClick.run(View.java:18422) 04-28 06:13:57.835: E/AndroidRuntime(2949): at android.os.Handler.handleCallback(Handler.java:733) 04-28 06:13:57.835: E/AndroidRuntime(2949): at android.os.Handler.dispatchMessage(Handler.java:95) – Suneel Kumar Apr 28 '14 at 10:31
  • what do you mean by strictmode etc – Suneel Kumar Apr 28 '14 at 10:33
  • please post your full code.I didn't understand your prblm yet – Maxwell Apr 28 '14 at 10:33