Java.lang.NullPointerException ao salvar dados para o banco

11 respostas
L

Olá! Estou fazendo um aplicativo para android e na hora de jogar os dados para o banco aparece o seguinte erro:
java.lang.NullPointerException

O trecho do código que atribui o valor ao banco é:

String urlPost="http://127.0.0.1/android.gravarComentarios.php";
    			//String urlGet="http://127.0.0.1/android.gravarNotas.php?idPousada="+txtIdPousada.getText().toString()+"&nota="+txtRatingValue.getText().toString();
    			ArrayList<NameValuePair> parametrosPost = new ArrayList<NameValuePair>();
    			parametrosPost.add(new BasicNameValuePair("idPousada", txtIdPousada.getText().toString())); //ver linhas
				parametrosPost.add(new BasicNameValuePair("comentario", txtComent.getText().toString()));
				String respostaRetornada = null;
				
				try {
					
					respostaRetornada = ConexaoHttpClient.executaHttpPost(urlPost, parametrosPost);
					//respostaRetornada = ConexaoHttpClient.executaHttpGet(urlGet);
					String resposta = respostaRetornada.toString();
					resposta = resposta.replaceAll("\\s+", "");
					if(resposta.equals("1")){
						mensagemExibir("Pousadas", "Comentário salvo!");
						Log.i("larissa", "oi, to aqui");
					}else
						mensagemExibir("Pousadas", "Erro! Seu comentário não foi salvo, tente novamente.");
					
				} catch (Exception erro) {
					
					//Toast.makeText(PousadasActivity.this, "Erro: "+erro, Toast.LENGTH_LONG);
					mensagemExibir("Erro", "Erro ao gravar: " +erro);
				}
	
			}

Alguém consegue ver onde está perdendo alguma referencia ou algo do tipo? Obrigada!

11 Respostas

Gleidson_Henrique

Coloque o erro que é gerado.

Abraços

L

Só aparece uma caixa de diálogo escrito java.lang.NullPointerException
No logcat do eclipse nao aparece nenhum erro.

ErickRAR

No catch, coloque erro.printStrackTrace(); para aparecer onde está o erro.

L
10-08 15:59:49.673: W/System.err(749): java.lang.NullPointerException

10-08 15:59:49.693: W/System.err(749): 	at com.pousadas.ConexaoHttpClient.getHttpClient(ConexaoHttpClient.java:29)

10-08 15:59:49.693: W/System.err(749): 	at com.pousadas.ConexaoHttpClient.executaHttpPost(ConexaoHttpClient.java:41)

10-08 15:59:49.714: W/System.err(749): 	at com.pousadas.PousadasActivity$5.onClick(PousadasActivity.java:174)

10-08 15:59:49.714: W/System.err(749): 	at android.view.View.performClick(View.java:3100)

10-08 15:59:49.723: W/System.err(749): 	at android.view.View$PerformClick.run(View.java:11644)

10-08 15:59:49.723: W/System.err(749): 	at android.os.Handler.handleCallback(Handler.java:587)

10-08 15:59:49.743: W/System.err(749): 	at android.os.Handler.dispatchMessage(Handler.java:92)

10-08 15:59:49.743: W/System.err(749): 	at android.os.Looper.loop(Looper.java:126)

10-08 15:59:49.743: W/System.err(749): 	at android.app.ActivityThread.main(ActivityThread.java:3997)

10-08 15:59:49.743: W/System.err(749): 	at java.lang.reflect.Method.invokeNative(Native Method)

10-08 15:59:49.763: W/System.err(749): 	at java.lang.reflect.Method.invoke(Method.java:491)

10-08 15:59:49.763: W/System.err(749): 	at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:841)

10-08 15:59:49.763: W/System.err(749): 	at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:599)

10-08 15:59:49.763: W/System.err(749): 	at dalvik.system.NativeStart.main(Native Method)
L

Essa é a classe q faz a conexão (ConexaoHttpClient.java)

public class ConexaoHttpClient {

	public static final int HTTP_TIMEOUT = 30 * 1000;
	private static HttpClient httpClient;
	
	private static HttpClient getHttpClient(){
		if(httpClient == null){
			final HttpParams httpParams = httpClient.getParams();
			HttpConnectionParams.setConnectionTimeout(httpParams, HTTP_TIMEOUT);
			HttpConnectionParams.setSoTimeout(httpParams, HTTP_TIMEOUT);
			ConnManagerParams.setTimeout(httpParams, HTTP_TIMEOUT);
		}
		return httpClient;
	}
	
	public static String executaHttpPost(String url, ArrayList<NameValuePair> parametrosPost) throws Exception{
		BufferedReader bufferedReader = null;
		
		try{
			HttpClient client = getHttpClient();
			HttpPost httpPost = new HttpPost(url);
			UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(parametrosPost);
			httpPost.setEntity(formEntity);
			HttpResponse httpResponse = client.execute(httpPost);
			bufferedReader = new BufferedReader(new InputStreamReader(httpResponse.getEntity().getContent()));
			StringBuffer stringBuffer = new StringBuffer("");
			String line = "";
			String LS = System.getProperty("line.separator"); // \s
			while ((line = bufferedReader.readLine()) != null){
				stringBuffer.append(line + LS);
			}
			bufferedReader.close();
			
			String resultado = stringBuffer.toString();
			return resultado;
		} finally{
			if(bufferedReader != null){
				try {
					bufferedReader.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
			
			
		}
	}
		
		
	
	public static String executaHttpGet(String url) throws Exception {
	 
	 
		BufferedReader bufferReader = null;
		
		try {
			HttpClient client = getHttpClient();
			HttpGet httpGet = new HttpGet(url);
			httpGet.setURI(new URI(url));
			HttpResponse httpResponse = client.execute(httpGet);
			bufferReader = new BufferedReader(new InputStreamReader(httpResponse.getEntity().getContent()));
			StringBuffer stringBuffer = new StringBuffer("");
			String line = "";
			String LS = System.getProperty("line.separator"); // \s
			while((line = bufferReader.readLine()) != null){
				stringBuffer.append(line + LS);
			}
			bufferReader.close();
			
			String resultado = stringBuffer.toString();
			return resultado;
		} finally{
			if(bufferReader != null){
				try{
					bufferReader.close();
				}catch (IOException e) {
					e.printStackTrace();
				}
			}
		}			
	}//method
ErickRAR

o NullPointer está na sua classe ConexaoHttpClient. Verifique as linhas 29 e 41 dessa classe.

edit: É essa linha aqui:

private static HttpClient getHttpClient(){  
        if(httpClient == null){  
            final HttpParams httpParams = httpClient.getParams();  //essa linha
...
        }  
        return httpClient;  
    }
L

não consgio ver o que está errado… fiz esse aplicativo seguindo um tutorial :confused:
oq poderia estar errado? esse null?

ErickRAR

Você deve pegar o httpClient de algum lugar.

private static HttpClient httpClient;   //aqui voce declara a variavel
      
    private static HttpClient getHttpClient(){  
        if(httpClient == null){  
            final HttpParams httpParams = httpClient.getParams();   //aqui você está tentando utiliza-la, porem o valor dela ainda é null.
...
...
..
        }  
        return httpClient;  
    }
L

Então, acho q sei oq fiz errado!
Estava seguindo videoaulas, só que não tinha a aula q ensinava a fazer essa conexão, então copiei de outr video que mostrava ja esse código pronto, mas nao mostrava o que tinha antes de:

private static HttpClient getHttpClient(){ if(httpClient == null){ . . .

e não faço ideia do que está faltando!
Depois q eu declarei a httpClient, eu deveria ter feito oq? tenho q instanciar?

L

me dá um exemplo pq eu realmente nao sei o que estou fazendo! (só preciso entregar isso) hahah

ErickRAR

Tente assim:

private static HttpClient getHttpClient() {  
        if (httpClient == null) {  
            httpClient = new DefaultHttpClient();  
            final HttpParams httpParamns = httpClient.getParams();  
...// o resto

        }  
        return httpClient;  
    }
Criado 8 de outubro de 2012
Ultima resposta 8 de out. de 2012
Respostas 11
Participantes 3